在Python中,如何像PHP的“self”关键字那样以静态方式泛型引用类?
在PHP中,类可以在静态上下文中使用“self”这个关键词,像这样:
<?php
class Test {
public static $myvar = 'a';
public static function t() {
echo self::$myvar; // Generically reference the current class.
echo Test::$myvar; // Same thing, but not generic.
}
}
?>
显然,我不能在Python中这样使用“self”,因为在Python里,“self”指的不是类,而是类的一个实例。那么,在Python中有没有办法在静态上下文中引用当前类,类似于PHP的“self”呢?
我觉得我想做的事情可能不太符合Python的风格。不过我不太确定,因为我刚开始学Python。这是我的代码(使用Django框架):
class Friendship(models.Model):
def addfriend(self, friend):
"""does some stuff"""
@staticmethod # declared "staticmethod", not "classmethod"
def user_addfriend(user, friend): # static version of above method
userf = Friendship(user=user) # creating instance of the current class
userf.addfriend(friend) # calls above method
# later ....
Friendship.user_addfriend(u, f) # works
我的代码运行得很正常。我只是想知道:在静态方法的第一行,有没有一个关键词可以替代“Friendship”?
这样的话,如果类名改变了,静态方法就不需要修改了。现在的情况是,如果类名改变,静态方法就得修改。
2 个回答
30
在所有情况下,self.__class__
代表的是一个对象的类。
http://docs.python.org/library/stdtypes.html#special-attributes
在非常少见的情况下,如果你想要处理静态方法,其实需要用到 classmethod。
class AllStatic( object ):
@classmethod
def aMethod( cls, arg ):
# cls is the owning class for this method
x = AllStatic()
x.aMethod( 3.14 )
37
这样做就可以了:
class C(object):
my_var = 'a'
@classmethod
def t(cls):
print cls.my_var
C.t()