I want to have simple class constants in python like this:
class FooBarBaz:
BAR = 123
@staticmethod
def getBar():
return BAR # this would not work, of course
return FooBarBaz.BAR # this would work but is "way too long"
Is there a shorter way to reference the class itself from inside a method, not the current instance? It's not only for static methods but in general, like a __class__
keyword or something.
You need @classmethod
rather than @staticmethod
- a class method will get passed a reference to the class (where a method will get self
), so you can look up attributes on it.
class FooBarBaz:
BAR = 123
@classmethod
def getBar(cls):
return cls.BAR
Actually, there is __class__
in python 3:
Python 3.2.3 (v3.2.3:3d0686d90f55, Apr 10 2012, 11:25:50)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... @staticmethod
... def foo():
... print(__class__)
...
>>> A.foo()
<class '__main__.A'>
>>>
See http://www.python.org/dev/peps/pep-3135 for the rationale why it has been added.
No idea about how to achieve the same in py2, I guess this is not possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With