1

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.

3
  • 1
    Hi there, can you include how you're planning on using the array (list) to switch throughout the class? Commented Dec 6, 2018 at 10:20
  • 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). Commented Dec 6, 2018 at 10:25
  • 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? Commented Dec 6, 2018 at 10:28

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

It.. didn't occur to me I can omit the class name within the namespace. That solved the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.