本文介绍了从静态方法访问静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从静态方法访问静态变量:
I want to access a static variable from a static method:
#!/usr/bin/env python
class Messenger:
name = "world"
@staticmethod
def get_msg(grrrr):
return "hello " + grrrr.name
print Messenger.get_msg(Messenger)
如何在不将grrrr
传递给方法的情况下执行此操作?这是真正的面向对象吗?..
How to do it without passing grrrr
to a method? Is this the true OOP?..
name
或self.name
之类的东西似乎都不起作用:
Anything like name
or self.name
seems not working:
NameError: global name 'name' is not defined
和
NameError: global name 'self' is not defined
推荐答案
使用@classmethod
代替@staticmethod
.在写完问题后才发现它.
Use @classmethod
instead of @staticmethod
. Found it just after writing the question.
在许多语言(C ++,Java等)中,静态"和类"方法是同义词. 不在Python中.
In many languages (C++, Java etc.) "static" and "class" methods are synonyms. Not in Python.
这篇关于从静态方法访问静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!