1
votes

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.

1
Hi there, can you include how you're planning on using the array (list) to switch throughout the class?TrebledJ
Assuming I have d as above, I can have integer i describe a state, so b and c would implement an abstract operation for states 0 and 1 respectively and then I can call d[i](self).Daniil Lantukhov
Ok, cool. Your workaround #1 seems like the most feasible. I don't see what's wrong with having to initialise different .b() and .c() functions (or reinitialise the d). Are your .b() and .c() common throughout the entire class?TrebledJ

1 Answers

4
votes

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)