Calling class variable with self

泪湿孤枕 提交于 2019-12-01 00:47:41

What is happening is that self.a refers to two things at different times.

When no instance variable exists for a name, Python will lookup the value on the class. So the value retrieved for self.a will be the class variable.

But when setting an attribute via self, Python will always set an instance variable. So now self.a is a new instance variable whose value is equal to the class variable + 1. This attribute shadows the class attribute, which you can no longer access via self but only via the class.

(One minor point, which has nothing to do with the question: you should never access double-underscore methods directly. Instead of calling something2.__str__(), call str(something2) etc.)

abcabc

Answer by Daniel Roseman clearly explains the problem. Here are some additional points and hope it helps. You can use type(self).a instead of self.a. Also look at the discussions Python: self vs type(self) and the proper use of class variables and Python: self.__class__ vs. type(self)

import numpy as np


class Something(object):
    a = np.random.randint(low=0, high=10)

    def do(self):
        type(self).a += 1
        print(type(self).a)

if __name__ == '__main__':
    something = Something()
    print(str(something ))
    something.do()
    something2 = Something()
    print(str(something2))
    something2.do()
    something3 = Something()
    print(str(something3))
    something3.do()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!