在 Python 中,如何以静态方式一般地引用类,例如 PHP 的“self”关键字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/738467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Python, how do I reference a class generically in a static way, like PHP's "self" keyword?
提问by Eddified
PHP classes can use the keyword "self" in a static context, like this:
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.
}
}
?>
Obviously I can't use "self" in this way in Python because "self" refers not to a class but to an instance. So is there a way I can reference the current class in a static context in Python, similar to PHP's "self"?
显然,我不能在 Python 中以这种方式使用“self”,因为“self”不是指一个类,而是指一个实例。那么有没有一种方法可以在 Python 的静态上下文中引用当前类,类似于 PHP 的“自我”?
I guess what I'm trying to do is rather un-pythonic. Not sure though, I'm new to Python. Here is my code (using the Django framework):
我想我正在尝试做的是相当不pythonic的。不过不确定,我是 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
My code works as expected. I just wanted to know: is there a keyword I could use on the first line of the static method instead of "Friendship"?
我的代码按预期工作。我只是想知道:有没有我可以在静态方法的第一行使用关键字而不是“友谊”的关键字?
This way if the class name changes, the static method won't have to be edited. As it stands the static method would have to be edited if the class name changes.
这样,如果类名更改,则不必编辑静态方法。就目前而言,如果类名更改,则必须编辑静态方法。
回答by Bastien Léonard
This should do the trick:
这应该可以解决问题:
class C(object):
my_var = 'a'
@classmethod
def t(cls):
print cls.my_var
C.t()
回答by S.Lott
In all cases, self.__class__
is an object's class.
在所有情况下,self.__class__
都是一个对象的类。
http://docs.python.org/library/stdtypes.html#special-attributes
http://docs.python.org/library/stdtypes.html#special-attributes
In the (very) rare case where you are trying to mess with static methods, you actually need classmethodfor this.
在(非常)罕见的情况下,您试图弄乱静态方法,您实际上需要classmethod来实现这一点。
class AllStatic( object ):
@classmethod
def aMethod( cls, arg ):
# cls is the owning class for this method
x = AllStatic()
x.aMethod( 3.14 )