test_value is a class variable shared by all instances. If you don’t want this behavior you can use instance variables which you can initialize in the __init__ method. See the docs:
Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # shared by all dogs
'canine'
>>> e.kind # shared by all dogs
'canine'
>>> d.name # unique to d
'Fido'
>>> e.name # unique to e
'Buddy'
these are all printing the id of 10. Because 10 is immutable, it is safe to just give all variables that have the value 10 a pointer to the place where Python stores the constant 10.
change 10 to 10.0 for further experiments.
so long as the class does not use slots, a.test_value first looks up a.__dict__["test_value"], then if that doesn’t exist it looks up type(a).test_value. That’s the case you’re seeing here. It is mostly safe, and more efficient than the alternative you’re proposing.
thanks a lot for reply,have read the docs,mine is a wrong grammar indeed, class attribute’s name should not be the same as the instance attribute’s name, or the latter will cover the former.
Not because it is immutable, so much as because small integers are pre-allocated, so you always get the same instance. @ayhanfuat 's answer is good. If you want a distinct variable for each instance then it is done like this:
class test:
def __init__(self):
self.test_value = 12.345
a = test()
b = test()
id(12.345), id(a.test_value), id(b.test_value)
(2706378293104, 2706378293168, 2706378293168)
The value 12.345 is not pre-allocated, but the instances a and b still point to one instance of it, because the code that was generated for __init__ only needs one copy of the constant.