如何在python中引用类本身

时间:2013-04-23 09:45:09

标签: python

我想在python中使用简单的类常量:

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"

是否有更短的方法从方法内部引用类本身,而不是当前实例?它不仅适用于静态方法,通常也适用于__class__关键字等。

2 个答案:

答案 0 :(得分:7)

您需要@classmethod而不是@staticmethod - 类方法将传递对类的引用(方法将获取self),因此您可以在其上查找属性

class FooBarBaz:
    BAR = 123

    @classmethod
    def getBar(cls):
        return cls.BAR

答案 1 :(得分:4)

实际上,python 3中有__class__

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'>
>>> 

请参阅http://www.python.org/dev/peps/pep-3135了解其添加原因。

不知道如何在py2中实现相同,我猜this is not possible