在Python中,如何像PHP的“self”关键字那样以静态方式泛型引用类?

2024-05-20 20:46:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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”,因为“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

我的代码按预期工作。我只想知道:在静态方法的第一行,有没有一个关键字可以代替“友谊”?

这样,如果类名更改,静态方法就不必编辑。如果类名改变,静态方法就必须被编辑。


Tags: thetestechoselffriend静态static关键字
2条回答

在所有情况下,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 )

这应该可以做到:

class C(object):
    my_var = 'a'

    @classmethod
    def t(cls):
        print cls.my_var

C.t()

相关问题 更多 >