Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference the class itself in python [duplicate]

Tags:

python

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.

like image 430
ddinchev Avatar asked Apr 23 '13 09:04

ddinchev


2 Answers

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
like image 58
babbageclunk Avatar answered Oct 04 '22 03:10

babbageclunk


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.

like image 39
georg Avatar answered Oct 04 '22 03:10

georg