Jump to content


Photo

Ch. 6 Initializing A Function With A Mutable List As Default Parameter?


  • Please log in to reply
No replies to this topic

#1 SergioF

SergioF

    New Member

  • Members
  • Pip
  • 1 posts

Posted 20 January 2014 - 08:49 AM

Hi.

In page 194, the code says:
class Athlete:
	def __init__(self, a_name, a_dob=None, a_times=[]):

This generates errors when a an instance of the class is initialized with the default value " [] " and later another instance is also initialized with the default value.

Example:
class Test:
    def __init__(self, items=[]):
        self.items=items

>>>t = Test()
>>>t.items.append("stuff")
>>>t.items
['stuff']
>>>t2 = Test()
>>>t2.items
['stuff']

Here is an explanation:
http://effbot.org/zo...ault-values.htm
which says that the correct way is to initialize mutable objects like this:
class Test2:
    def __init__(self, items=None):
        if items:
           self.items=items
        else:
           self.items = []

This is not in the errata, so I guess it's not corrected.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users