List Info

Thread: default parameters in classes




default parameters in classes
country flaguser name
United States
2007-03-12 06:52:19
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/
_______________________________________________
Tutor maillist  -  Tutorpython.org
http://
mail.python.org/mailman/listinfo/tutor

Re: default parameters in classes
country flaguser name
United States
2007-03-12 07:29:44
J Greg wrote:
> 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?

http://www.effbot.org/pyfaq/why-are
-default-values-shared-between-objects.htm

Kent
_______________________________________________
Tutor maillist  -  Tutorpython.org
http://
mail.python.org/mailman/listinfo/tutor

Re: default parameters in classes
country flaguser name
United States
2007-03-12 13:03:39
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?

_______________________________________________
Tutor maillist  -  Tutorpython.org
http://
mail.python.org/mailman/listinfo/tutor

[1-3]

about | contact  Other archives ( Real Estate discussion Medical topics )