[Tutor] default parameters in classes
J Greg
juinsana at yahoo.com
Mon Mar 12 12:52:19 CET 2007
I want my object to create a fresh dictionary if its
not passed one.
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?
class newobj:
def __init__(self, labl, d = {} ):
print labl, d, '\n' # print the dictionary as
passed, or freshly created
if d.has_key('obj1'):
d['obj2'] = 'very dirty'
d['obj1'] = 'dirty'
#-----------------------------------------------------------------
# Create 4 instances of an object
# If the parent doesn't already have a dictionary,
create one
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
"""
Prints this:
obj1: {}
obj2: {'obj1': 'dirty'}
obj3: {'obj3': True}
obj4: {'obj1': 'dirty', 'obj2': 'very dirty'}
"""
____________________________________________________________________________________
It's here! Your new message!
Get new email alerts with the free Yahoo! Toolbar.
http://tools.search.yahoo.com/toolbar/features/mail/
More information about the Tutor
mailing list