Search code examples
pythonclass-variablesfirst-class-functions

Initializing a class variable with array of class functions


I would like to create an array of member functions as a class variable so I can switch throughout the class etc. The following doesn't work

class A:
    def b(self):
        pass

    def c(self):
        pass

    d = [A.b, A.c]

because A is not yet created. Is there a workaround for that? I've managed to think of two: 1) initialize the class variable in __init__ which I don't like because it will cause it to be reinitialized with every object created; and 2) create it as global variable which I also don't like since it's only used within the class and so should be a class variable.


Solution

  • You can't use A.b there since, as you say, A isn't done being defined yet. But you can pick up the functions by their name from the namespace directly:

    class A:
        def b(self):
            pass
    
        def c(self):
            pass
    
        d = [b, c]
    

    However, this does not help you, because now you have a list of unbound methods:

    >>> A().d[0]()
    TypeError: b() missing 1 required positional argument: 'self'
    

    If you want a list of bound methods (where self is implicitly passed as the current instance), you'll need to create that list when you have an actual instance:

    class A:
        def __init__(self):
            self.d = [self.b, self.c]
    
        ...
    

    Alternatively you'll need to pass self explicitly to the unbound method:

    class A:
        ...
    
        d = [b, c]
    
        def foo(self):
            self.d[0](self)