如果这个问题很明显,请原谅我,但从我在Python的OOP教程中读到的内容,他们都没有提到如何让静态变量存储静态方法。在我的代码中,我尝试了:
class Features:
a_static_variable = 1
a_static_variable_that_references_a_static_function = Features.func1
@staticmethod
def func1(blah):
print(blah)
尝试运行时,我收到了:
NameError: name 'Features' is not defined
类方法是否可以在自己的类中引用静态方法?如果是这样,我该怎么做。我尝试用无事物和自我替换功能,但正如我所预期的那样没有任何意义。
答案 0 :(得分:4)
这只是func1
尚未定义的情况。
如果您重新订购,它应该有效:
class Features:
a_static_variable = 1
@staticmethod
def func1(blah):
print(blah)
a_static_variable_that_references_a_static_function = func1
答案 1 :(得分:2)
是的,首先定义函数:
class Features:
@staticmethod
def func1(blah):
print(blah)
a_static_variable = 1
a_static_variable_that_references_a_static_function = func1
Features.a_static_variable_that_references_a_static_function('test')
答案 2 :(得分:1)
您的代码有两个错误(在其他答案中有解释)。这个例子可以帮助您了解正在发生的事情。
class Example:
class_variable = 'class_variable'
@staticmethod
def static_method():
print('static_method')
class_method = static_method
print(locals())
def instance_method(self):
print(instance_method)
print(locals())
运行此代码时,如果不实例化此类的成员,则输出为:
creating the class:
{'class_variable': 'class_variable',
'__module__': '__main__',
'static_method': <staticmethod object at 0x0135E5F0>,
'class_method': <staticmethod object at 0x0135E5F0>
}
因此,在创建类时,会创建一个范围,可以访问该字典中的所有名称。
现在让我们来看看当我们这样做时会发生什么:
example = Example()
example.instance_method()
实例化对象时没有任何反应,但调用instance_method
将打印该范围可访问的局部变量。
instance_method
{'self': <__main__.Example instance at 0x01810210>}
现在,您可能习惯于创建引用类变量的实例方法。
def other_instance_method(self):
print(Example.class_variable)
此处,本地范围内不存在Example
。为了找到它,需要搜索全局范围(即globals
)。请注意,我们可以从Example
对象本身访问类变量,而不是显式引用self
。
def other_instance_method(self):
print(self.class_variable)
您可以通过从各个地方打印locals()
和globals()
来自行进行一些测试,以掌握范围的变化。