[Tutor] Python Gotcha - List Question

Guess?!? wtfwhoami at gmail.com
Tue Jun 17 06:14:35 CEST 2008


Exercise 17.6 Write a definition for a class named Kangaroo with the
following methods:
1. An init method that initializes an attribute named pouch contents to an
empty list.
2. A method named put in pouch that takes an object of any type and adds it to
pouch contents.
Test your code by creating two Kangaroo objects, assigning them to
variables named
kanga and roo, and then adding roo to the contents of kanga's pouch.

class Kangaroo:
    def __init__(self, pouch_contents=None):
        if pouch_contents is None:
            pouch_contents = []
        else:
            self.pouch_contents = pouch_contents


    def put_in_pouch(self,obj):
        self.pouch_contents.append(obj)
        return self.pouch_contents

kanga = Kangaroo([1,2])
roo = Kangaroo([3,4])

print kanga,roo
print kanga.put_in_pouch(roo.pouch_contents)

**************
<__main__.Kangaroo instance at 0x00A9A878> <__main__.Kangaroo instance
at 0x00A9A8A0>
[1, 2, [3, 4]]
**************


when I modify as

class Kangaroo:
    def __init__(self, pouch_contents=None):
        if pouch_contents is None:
            pouch_contents = []
        else:
            self.pouch_contents = pouch_contents


    def put_in_pouch(self,obj):
        self.pouch_contents.append(obj)
        return self.pouch_contents

kanga = Kangaroo()
roo = Kangaroo()

print kanga,roo
print kanga.put_in_pouch(roo)


I get error which states ... empty list never got formed ....

<__main__.Kangaroo instance at 0x00A9A878> <__main__.Kangaroo instance
at 0x00A9A8A0>
Traceback (most recent call last):
  File "C:\Documents and
Settings\Gagan\workspace\PythonWork\src\Kangaroo.py", line 17, in
<module>
    print kanga.put_in_pouch(roo)
  File "C:\Documents and
Settings\Gagan\workspace\PythonWork\src\Kangaroo.py", line 10, in
put_in_pouch
    self.pouch_contents.append(obj)
AttributeError: Kangaroo instance has no attribute 'pouch_contents'


Where Am I acting as NewBie :)?


More information about the Tutor mailing list