1

I am new to python3 and tring to build a sqlobject class which named whatever. Then I created a function to caculate the average of one column. Here are parts of the codes.

class whatever(sqlobject.SQLObject):
    _connection = connection
    f1 = sqlobject.FloatCol()
    f2 = sqlobject.FloatCol()
    wid=sqlobject.IntCol(default=None)


def avg(col, num):
    l1 = []
    for i in range(1,num):
        e = whatever.get(i).col
        l1.append(a)
    return statistics.mean(l1)



print (avg(f1, 5))

But it returns the error:

Traceback (most recent call last):
  File "test1.py", line 58, in <module>
    print (avg(f1, 5))
NameError: name 'f1' is not defined

However, when I directly wrote down the code like this:

class whatever(sqlobject.SQLObject):
    _connection = connection
    f1 = sqlobject.FloatCol()
    f2 = sqlobject.FloatCol()
    wid=sqlobject.IntCol(default=None)

l1 = []
for i in range(1,5):
    e = whatever.get(i).f1
    l1.append(e)
print (statistics.mean(l1))

It works fine. So what should I do with the def avg(col, num) function?

phd
  • 82,685
  • 13
  • 120
  • 165
Ze Xu
  • 13
  • 2

1 Answers1

0

Please note that whatever.get(i).f1 works — this because you name the column explicitly. If you want to get a column by name you have to:

  • pass the name of the column, i.e. avg('f1', 5);
  • get the value for the column using getattr.

So the fixed code is:

def avg(col, num):
    l1 = []
    for i in range(1, num):
        e = getattr(whatever.get(i), col)
        l1.append(a)
    return statistics.mean(l1)

print(avg('f1', 5))

PS. The next error in your code will be NameError: a. What is a? Do you mean e?

phd
  • 82,685
  • 13
  • 120
  • 165
  • Thank you so much! I didn't even know there is a function called getattr(), that "a" is a mistake, it is a "e". Thanks again! – Ze Xu Apr 09 '18 at 22:55