How would you I came up with this interesting (at least to me) example.
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()
The above prints the following in the console:
$ python test.py
<__main__.Something object at 0x7f03a80e0518>
1
<__main__.Something object at 0x7f03a80cfcc0>
1
<__main__.Something object at 0x7f03a80cfcf8>
1
I'm a bit confused because I (wrongly) assumed the value of a
would have increased.
I'm able to obtain the behaviour I would expect if I use the @classmethod
decorator.
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()
This correctly prints the following in the console.
python test.py
<__main__.Something object at 0x7faac77becc0>
3
<__main__.Something object at 0x7faac77becf8>
4
<__main__.Something object at 0x7faac77c3978>
5
Now, I'm wondering in the first example, when I'm calling self.a
, what I'm accessing? It's not a class variable since I don't seem to be able to change its value. It's not an instance variable either, since this seems to be shared among different objects of the same class. How would you call it?
Is this a class variable that I'm using in the wrong way? I know the cls
name if a convention, so maybe I'm truly accessing a class variable, but I'm not able to change its value because I haven't decorate the method with the @classmethod
decorator.
Is this a sort of illegitimate use of the language? I mean something it's best practice to not do in order to avoid introduce a bug on a later stage?