【发布时间】:2020-02-17 17:21:31
【问题描述】:
我从 Python 的类开始,我想做这样的事情:
class First:
def __init__(self):
self.value = 1
@classmethod
def func(cls):
print(self.value)
second = First()
second.func()
但我无法访问班级的self.value。有人可以帮帮我吗?
【问题讨论】:
-
当使用
classmethod时,你想通过cls而不是self。但是类方法不能也不应该依赖于实例的状态。 stackoverflow.com/questions/12179271/… -
@classmethods 取cls,这是类。如果你想使用self这是对象实例,请移除装饰器。
标签: python class methods attributes