I created the following example to understand the instances in python
import time;
class test:
mytime = time.time();
def __init__(self):
#self.mytime = time.time();
time.sleep(1);
pass
from test import test
test1 = test()
test2 = test()
print test1.mytime
print test2.mytime
test1.mytime = 12
print test1.mytime
print test2.mytime
in this case the output id the following:
1347876794.72
1347876794.72
12
1347876794.72
I expected that the test2.mytime is bigger with 1 second than the test1.mytime. Why doesn’t created a copy about the mytime in each instance?
Let’s look at those lines:
Here you set class member value, which is calculated once when class definition is executed, so
time.time()is calculated once when module that containsclass testis loaded.Every instance of the
class testwill receive that precalculated value and you must override that value (e.g. in __init__ method), accessing it viaself(which is a special argument that stores reference to an instance), thus setting instance member value.