6. Built-in Types — Python v2.6.2 documentation
Python variables contain pointers to the data, not the data itself--this one of the more confusing aspects of the language for many. The implications of this, though, may be made clear by the following example:

Python variables contain pointers to the data, not the data itself--this one of the more confusing aspects of the language for many. The implications of this, though, may be made clear by the following example:
class mytester(object):
def __init__(self, thingone={}, thingtwo=None):
self.thingone = thingone
if isinstance(thingtwo,dict):
self.thingtwo = thingtwo
else:
self.thingtwo = {}
def setone(self, **kwargs):
self.thingone.update(kwargs)
return self
def settwo(self, **kwargs):
self.thingtwo.update(kwargs)
return self
t1 = mytester()
t2 = mytester()
print(t1.thingone, t2.thingone)
# ({}, {})
print(t1.thingtwo, t2.thingtwo)
# ({}, {})
t1.settwo(say='hi').settwo(to='thing one and thing two') # set thingtwo for t1
# <__main__.mytester object at 0xecc9d0>
print(t1.thingtwo, t2.thingtwo) # t1 & t2 remain independent
# ({'to': 'thing one and thing two', 'say': 'hi'}, {})
t1.setone(say='hi').setone(to='thing one and thing two') # set thingone for t1
# <__main__.mytester object at 0xecc9d0>
print(t1.thingone, t2.thingone) # thingone dict points to same object for each
# ({'to': 'thing one and thing two', 'say': 'hi'}, {'to': 'thing one and thing two', 'say': 'hi'})
print id(t1.thingone), id(t2.thingone) #they're the same object!
# (15704976, 15704976)
print id(t1.thingtwo), id(t2.thingtwo) #they're not!
# (9733440, 9733584)
In the first instance, the 'thingone' attribute of the class, initializing it with the default '={}' creates a pointer to a dictionary object called 'thingone' (NOT self.thingone). So, when you change the values in that object for one class, you change them for all.
One could see where the ability to do this would be useful (say, where you would a singleton pattern in C++, for example). Still, in general the ability to pass a value to the __init__ method of class implies to the user that the values will be unique for each instance of the class--so the pattern used for 'thingtwo' should be used more often.
Also, this exercise highlights the importance of the id() function in Python--it clarifies a lot of things.

No comments:
Post a Comment