List the class methods in the class instance

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]
+4
source share
2 answers

foo (self) :

In [1]: class A:
   ...:     def a(self):
   ...:         return 1
   ...:     def b(self):
   ...:         return 2
   ...:     def c(self):
   ...:         return 3
   ...:     

In [2]: foo = A()

In [3]: l = [A.a, A.b, A.c]

In [4]: [f(foo) for f in l]
Out[4]: [1, 2, 3]
+2

, , , , - .

>>> foo = A()
>>> l = [foo.a, foo.b, foo.c]
>>> [f() for f in l]
[1, 2, 3]

, A

>>> foo.a
<bound method A.a of <__main__.A object at 0x02F381B0>>
>>> A.a
<function A.a at 0x02F361E0>
+4

All Articles