How can I access a classmethod from inside a class in Python

At the time that x=10 is executed in your example, not only does the class not exist, but the classmethod doesn’t exist either.

Execution in Python goes top to bottom. If x=10 is above the classmethod, there is no way you can access the classmethod at that point, because it hasn’t been defined yet.

Even if you could run the classmethod, it wouldn’t matter, because the class doesn’t exist yet, so the classmethod couldn’t refer to it. The class is not created until after the entire class block runs, so while you’re inside the class block, there’s no class.

If you want to factor out some class initialization so you can re-run it later in the way you describe, use a class decorator. The class decorator runs after the class is created, so it can call the classmethod just fine.

>>> def deco(cls):
...     cls.initStuff()
...     return cls
>>> @deco
... class Foo(object):
...     x = 10
...     
...     @classmethod
...     def initStuff(cls):
...         cls.x = 88
>>> Foo.x
88
>>> Foo.x = 10
>>> Foo.x
10
>>> Foo.initStuff() # reinitialize
>>> Foo.x
88

Leave a Comment