你会如何想出这个有趣的(至少对我来说)例子。
import numpy as np
class Something(object):
a = np.random.randint(low=0, high=10)
def do(self):
self.a += 1
print(self.a)
if __name__ == '__main__':
something = Something()
print(something.__str__())
something.do()
something2 = Something()
print(something2.__str__())
something2.do()
something3 = Something()
print(something3.__str__())
something3.do()
以上在控制台中打印以下内容:
$ python test.py
<__main__.Something object at 0x7f03a80e0518>
1
<__main__.Something object at 0x7f03a80cfcc0>
1
<__main__.Something object at 0x7f03a80cfcf8>
1
我有点困惑,因为我(错误地)假设了a
会增加。
如果我使用的话,我可以获得我期望的行为@classmethod
装饰师。
import numpy as np
class Something(object):
a = np.random.randint(low=0, high=10)
@classmethod
def do(cls):
cls.a += 1
print(cls.a)
if __name__ == '__main__':
something = Something()
print(something.__str__())
something.do()
something2 = Something()
print(something2.__str__())
something2.do()
something3 = Something()
print(something3.__str__())
something3.do()
这会在控制台中正确打印以下内容。
python test.py
<__main__.Something object at 0x7faac77becc0>
3
<__main__.Something object at 0x7faac77becf8>
4
<__main__.Something object at 0x7faac77c3978>
5
现在,我想知道在第一个例子中,当我打电话时self.a
,我正在访问什么?它不是一个类变量,因为我似乎无法更改它的值。它也不是实例变量,因为它似乎在同一类的不同对象之间共享。你会怎么称呼它?
这是我使用错误方式使用的类变量吗?我知道cls
name 如果是一个约定,所以也许我真正访问了一个类变量,但我无法更改它的值,因为我还没有用@classmethod
装饰师。
这是一种非法使用该语言吗?我的意思是最好不要做一些事情,以避免在后期引入错误?