Search code examples
pythonlist-comprehensionclass-method

Perform list of class methods on instance of class


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 A's methods on an instance of A? I tried the following

>>> foo = A()
>>> l = [A.a, A.b, A.c]

When I tried a list comprehension 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 just one of the items in the list, it should be a function object

>>> A.a
<function A.a at 0x02F361E0>

So how can I call the function on the instance in the list comprehension? It thinks that I am trying to call a method f, rather than having f take on the values of each of the function objects in l.

What I expect the output to be is

[1, 2, 3]

Solution

  • It is also possible to pass foo object as first (self) argument:

    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]