[Tutor] Problem with calling class methods stored in a list
Peter Otten
__peter__ at web.de
Thu Jan 10 12:00:19 CET 2013
Tobias Marquardt wrote:
> Hello,
>
> I have a class with some class methods that are also stored in a list.
> Now I have a problem calling these methods.
> Essentially the relevant code looks like this:
>
> class MyClass(object):
>
> @classmethod
> def foo(cls):
> cls.method_list[0]()
>
> @classmethod
> def bar(cls):
> print("Hello World")
>
> method_list = [bar]
At this point MyClass is not yet defined, so bar has no information about
it.
> So foo() takes bar() from the list and tries calls it, which results in
> an error:
>
> File "aco/antsystem/test.py", line 11, in foo
> cls.method_list[0]()
> TypeError: 'classmethod' object is not callable
>
> I guess the reason is that bar() needs to be called on the class like:
> cls.bar(), but how to I achieve this here?
> Any suggestions?
Build the list outside the class:
MyClass.method_list = [MyClass.bar]
More information about the Tutor
mailing list