On 06/08/2011 01:09 PM, Cathy James wrote:
I am almost there, but I need a little help:
I would like to
a) print my dogs in the format index. name: breed as follows:
0. Mimi:Poodle
1.Sunny: Beagle
2. Bunny: German Shepard
I am getting
(0, ('Mimi', 'Poodle')) . Mimi : Poodle instead-what have I done wrong?
b) I would like to append to my list, but my line dogs.dogAppend() is
giving a TypeError:
for i in enumerate (self.dogAppend()):
TypeError: 'list' object is not callable
Any help?
#MY CODE BELOW:
import sys
Not needed in the class definition, move it to the "if __name__..." section.
Actually, it's not needed at all. That part could be rewritten to avoid the need for sys.exit()
entirely.
class Dog():
def __init__(self, name, breed):
self.name = name
self.breed = breed
def dogAppend(self):
self.dogAppend = []
self.dogAppend.append((self.name,self.breed))
return self.dogAppend
1: Think about what you're trying to do here... You seem to want _each_ instance of Dog to
hold the whole list. Do you want Dog to be an individual Dog or do you want it to be a list of
Dogs? You can't do both in a single class.
2: This won't work to append to your list anyway... each time you call dogAppend() it will
clear out any existing list and result in a list of one element, a tuple of (name, breed). You
can do exactly the same thing with a single line: return [(self.name, self.breed)]
def display (self):
for i in enumerate (self.dogAppend()):
print (i,".", self.name, ": " + self.breed)
Misusing enumerate. Check the docs.
http://docs.python.org/py3k/library/functions.html?highlight=enumerate#enumerate
Besides that, there are easier ways to print the contents of a list.
if __name__ == "__main__":
dogs = Dog(name=input (" Enter Dog Name: "), breed=input ("Enter
Dog Breed: "))
while not dogs:
print("Goodbye!!")
sys.exit()
else:
else does not belong with while.
#dogs.dogAppend()
dogs.display()
Here's one possible replacement. There are many other approaches as well.
(This leaves the individual dogs as a (name, breed) tuple. It could be modified for other
definitions of a dog. -- Exercise left for the reader...) ;-)
class DogKennel:
def __init__(self):
self.dogs = [] # list of dogs
def addDog(self):
name = input("Enter dog name: ")
if name == "":
return False
breed = input("Enter dog breed: ")
if breed == "":
return False
self.dogs.append((name, breed)) # Append this dog tuple to the list
return True
def display(self):
i = 1
for dog in self.dogs:
print("%d. %s: %s" % (i, dog[0], dog[1]))
i += 1;
if __name__ == "__main__":
dogs = DogKennel()
while (dogs.addDog()):
pass
dogs.display()
-=- Larry -=-
--
http://mail.python.org/mailman/listinfo/python-list