[Tutor] default parameters in classes
Terry Carroll
carroll at tjc.com
Mon Mar 12 19:03:39 CET 2007
On Mon, 12 Mar 2007, J Greg wrote:
> Perhaps I don't understand. In the example below, the
> first instance correctly creates a fresh dictionary.
> But the second instance seems to inherit the now dirty
> dictionary from the first instance.
>
> What am I missing?
This is a very common Python "gotcha," passing mutable objects as default
arguments to a function. If you do a google search on "python gotchas" it
will show up in pretty much every list of gotchas.
The idiom to get around this is to instead use a default value of None,
and then, if you actually see None in the function, set it equal to the
real default argument you want, i.e.:
class newobj:
def __init__(self, labl, d = None ): # changed line
if d is None: # added line
d = {} # added line
print labl, d, '\n'
# print the dictionary as passed, or freshly created
if d.has_key('obj1'):
d['obj2'] = 'very dirty'
d['obj1'] = 'dirty'
Now your code:
obj1 = newobj('obj1:') # ok
obj2 = newobj('obj2:') # gets the dirty dictionary from obj1
dd = dict(obj3=True)
obj3 = newobj('obj3:', dd) # ok
obj4 = newobj('obj4:') # get a dirty dictionary from obj2
Gets:
obj1: {}
obj2: {}
obj3: {'obj3': True}
obj4: {}
Is that more what you were expecting?
More information about the Tutor
mailing list