If you have a class with several methods, for example
class A:
def a(self):
return 1
def b(self):
return 2
def c(self):
return 3
How could you call a sequence of methods Ain an instance A? I tried the following
>>> foo = A()
>>> l = [A.a, A.b, A.c]
When I tried to figure out a list to call each of these methods, I get the following error
>>> [foo.f() for f in l]
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
[foo.f() for f in l]
File "<pyshell#21>", line 1, in <listcomp>
[foo.f() for f in l]
AttributeError: 'A' object has no attribute 'f'
If I look at only one of the elements in the list, it must be a function object
>>> A.a
<function A.a at 0x02F361E0>
So how can I call a function on an instance in list comprehension? He thinks I'm trying to call a method f, instead of ftaking the values of each of the function's objects in l.
It is expected that the result will be
[1, 2, 3]
source
share