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
我的代码按预期工作。我只想知道:在静态方法的第一行,有没有一个关键字可以代替“友谊”?
这样,如果类名更改,静态方法就不必编辑。如果类名改变,静态方法就必须被编辑。
在所有情况下,
self.__class__
都是对象的类。http://docs.python.org/library/stdtypes.html#special-attributes
在(非常)罕见的尝试使用静态方法的情况下,实际上需要classmethod来实现这一点。
这应该可以做到:
相关问题 更多 >
编程相关推荐