[英]Access static class variable in instance method
假设我将类Test
定义为:
class Test
test_var = 2
def test_func():
print(test_var)
我可以找到什么test_var
像这样:
>>> Test.test_var
2
...但是调用Test.test_func()
不起作用。
>>> Test.test_func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in test
NameError: name 'test_var' is not defined
如果我这样更改Test.test_func()
(请注意,这是伪代码):
redef test_func():
print(Test.test_var)
它工作正常:
>>> Test.test_func()
2
...这是有道理的。 但是, 要记住我希望test_func作为实例方法 ,如何使第一个示例工作?
请注意,上面发布的代码是示例代码,因此应忽略错别字。
您始终可以通过实例(即self
访问类级别的属性,只要您没有用相同名称的实例属性对其进行遮盖即可。 所以:
def test_func(self):
print(self.test_var)
您需要将self(几乎总是您想要的)传递给类方法,或者如果不需要self,则添加@classmethod或@staticmethod装饰器。 然后创建该类的实例并调用test_func方法。
Examples:
# test_var is an class variable and test_func has a classmethod decorator
>>> class Test:
... test_var = 2
... @classmethod
... def test_func(cls):
... print(cls.test_var)
...
>>> t = Test()
>>> t.test_func()
2
# test_var is an class variable and test_func has a staticmethod decorator
>>> class Test:
... test_var = 2
... @staticmethod
... def test_func():
... print(Test.test_var)
...
>>> t = Test()
>>> t.test_func()
2
# test_var is an instance variable here
>>> class Test:
... self.test_var = 2
... def test_func(self):
... print(self.test_var)
...
>>> t = Test()
>>> t.test_func()
2
在您的示例中, test_func
只是一个函数,尽管它是在类名称空间中定义的,但函数本身并不知道类名称空间。 您需要常规实例方法或类方法。
class Test:
test_var = 2
def instance_test(self):
# instance methods will look in self first and class namespace second
print(self.test_var)
@classmethod
def class_test(cls):
# class methods take the class itself as first argument
print(cls.test_var)
t = Test()
t.instance_test()
Test.class_test()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.