Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #7254 > unrolled thread
| Started by | Cathy James <nambo4jb@gmail.com> |
|---|---|
| First post | 2011-06-08 15:09 -0500 |
| Last post | 2011-06-09 23:07 -0700 |
| Articles | 7 — 5 participants |
Back to article view | Back to comp.lang.python
Of Functions, Objects, and Methods-I NEED HELP PLEASE Cathy James <nambo4jb@gmail.com> - 2011-06-08 15:09 -0500
Re: Of Functions, Objects, and Methods-I NEED HELP PLEASE John Gordon <gordon@panix.com> - 2011-06-08 20:42 +0000
Re: Of Functions, Objects, and Methods-I NEED HELP PLEASE Larry Hudson <orgnut@yahoo.com> - 2011-06-08 23:59 -0700
Re: Of Functions, Objects, and Methods-I NEED HELP PLEASE Ethan Furman <ethan@stoneleaf.us> - 2011-06-09 05:54 -0700
Re: Of Functions, Objects, and Methods-I NEED HELP PLEASE Ethan Furman <ethan@stoneleaf.us> - 2011-06-09 06:10 -0700
Re: Of Functions, Objects, and Methods-I NEED HELP PLEASE Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2011-06-09 10:25 -0700
Re: Of Functions, Objects, and Methods-I NEED HELP PLEASE Larry Hudson <orgnut@yahoo.com> - 2011-06-09 23:07 -0700
| From | Cathy James <nambo4jb@gmail.com> |
|---|---|
| Date | 2011-06-08 15:09 -0500 |
| Subject | Of Functions, Objects, and Methods-I NEED HELP PLEASE |
| Message-ID | <mailman.30.1307563778.11593.python-list@python.org> |
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
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
def display (self):
for i in enumerate (self.dogAppend()):
print (i,".", self.name, ": " + self.breed)
if __name__ == "__main__":
dogs = Dog(name=input (" Enter Dog Name: "), breed=input ("Enter
Dog Breed: "))
while not dogs:
print("Goodbye!!")
sys.exit()
else:
#dogs.dogAppend()
dogs.display()
[toc] | [next] | [standalone]
| From | John Gordon <gordon@panix.com> |
|---|---|
| Date | 2011-06-08 20:42 +0000 |
| Message-ID | <isomrg$b3g$1@reader1.panix.com> |
| In reply to | #7254 |
In <mailman.30.1307563778.11593.python-list@python.org> Cathy James <nambo4jb@gmail.com> writes:
> 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
> def dogAppend(self):
> self.dogAppend = []
You have a method and a list that are both called dogAppend. Try naming
one of them something different.
--
John Gordon A is for Amy, who fell down the stairs
gordon@panix.com B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
[toc] | [prev] | [next] | [standalone]
| From | Larry Hudson <orgnut@yahoo.com> |
|---|---|
| Date | 2011-06-08 23:59 -0700 |
| Message-ID | <rqednZoL2ezK8m3QnZ2dnUVZ5hKdnZ2d@giganews.com> |
| In reply to | #7254 |
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 -=-
[toc] | [prev] | [next] | [standalone]
| From | Ethan Furman <ethan@stoneleaf.us> |
|---|---|
| Date | 2011-06-09 05:54 -0700 |
| Message-ID | <mailman.52.1307624146.11593.python-list@python.org> |
| In reply to | #7276 |
Larry Hudson wrote:
> On 06/08/2011 01:09 PM, Cathy James wrote:
>> Dog Breed: "))
>> while not dogs:
>> print("Goodbye!!")
>> sys.exit()
>> else:
>
> else does not belong with while.
else works just fine with while; it is the path taken when the while is
exhausted, but not broken out of:
--> i = 5
--> while i:
... print(i)
... i -= 1
... else:
... print("blast off!")
...
5
4
3
2
1
blast off!
--> i = 5
--> while i:
... print(i)
... i -= 1
... if i == 3:
... print('aborting')
... break
... else:
... print("blast off!")
...
5
4
aborting
~Ethan~
[toc] | [prev] | [next] | [standalone]
| From | Ethan Furman <ethan@stoneleaf.us> |
|---|---|
| Date | 2011-06-09 06:10 -0700 |
| Message-ID | <mailman.53.1307625097.11593.python-list@python.org> |
| In reply to | #7276 |
Ethan Furman wrote:
> Larry Hudson wrote:
>> On 06/08/2011 01:09 PM, Cathy James wrote:
>>> Dog Breed: "))
>>> while not dogs:
>>> print("Goodbye!!")
>>> sys.exit()
>>> else:
>>
>> else does not belong with while.
>
> else works just fine with while; it is the path taken when the while is
> exhausted, but not broken out of:
It works with 'for' as well.
~Ethan~
[toc] | [prev] | [next] | [standalone]
| From | Dennis Lee Bieber <wlfraed@ix.netcom.com> |
|---|---|
| Date | 2011-06-09 10:25 -0700 |
| Message-ID | <mailman.56.1307640355.11593.python-list@python.org> |
| In reply to | #7276 |
On Wed, 08 Jun 2011 23:59:35 -0700, Larry Hudson <orgnut@yahoo.com>
declaimed the following in gmane.comp.python.general:
> > 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
>
> 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)]
>
Worse than that... The first time dogAppend is called on an instance
of Dog, it replaces the dogAppend method with a binding to the (single
element) list created by the method.
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed@ix.netcom.com HTTP://wlfraed.home.netcom.com/
[toc] | [prev] | [next] | [standalone]
| From | Larry Hudson <orgnut@yahoo.com> |
|---|---|
| Date | 2011-06-09 23:07 -0700 |
| Message-ID | <WvadnQoO0YomKWzQnZ2dnUVZ5u6dnZ2d@giganews.com> |
| In reply to | #7276 |
On 06/08/2011 11:59 PM, Larry Hudson wrote:
> On 06/08/2011 01:09 PM, Cathy James wrote:
>> I am almost there, but I need a little help:
>>
>> I would like to
>>
... <deleted text>
> 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...) ;-)
>
... <more deleted text>
In thinking about this some more, I thought a dictionary instead of a list would be a better fit
for this example. For one thing, it allows accessing the dogs by name instead of an arbitrary
index number. But remember that a dictionary is unordered -- it won't be displayed in the same
order that the entries were made.
Here's this approach, rewritten (and slightly expanded) using a dictionary.
class DogKennel:
def __init__(self):
"""Dog names/breeds kept in a dictionary"""
self.dogs = {}
def addDog(self):
"""Add a single dog to the dictionary"""
name = input("Enter dog's name: ")
if name == "": # Abort with empty input
return False
breed = input("Enter dog's breed: ")
if breed == "": # Abort here if needed also
return False
self.dogs[name] = breed
return True
def makeKennel(self):
"""Add multiple dogs (a pack?) to the dictionary"""
while self.addDog():
pass
def getDog(self, name=""):
"""Get the dog's breed by its name"""
if name in self.dogs:
return self.dogs[name]
else:
return None
def display(self):
"""Display all the dogs in the kennel (the dictionary)"""
i = 1
for dog in self.dogs.keys():
print("%2d. %s: %s" % (i, dog, self.dogs[dog]))
i += 1
# Note this is a normal function, NOT a member function of DogKennel.
# It probably should go in the __main__ section to keep it separate from
# the DogKennel class. (This would be significant only if you're going
# to import the DogKennel class into other programs.)
def yesno(prompt = ""):
"""Get a yes or no answer. Returns True if yes, False if no"""
if prompt != "":
prompt = prompt + " (y/n) "
while True:
ans = input(prompt).upper()
if ans != "": # Answer is not empty
if ans[0] == 'Y': # 1st char is 'Y'?
return True
if ans[0] == 'N': # 1st char is 'N'?
return False
# Otherwise loop back for another go
if __name__ == "__main__":
dogs = DogKennel()
dogs.makeKennel()
dogs.display()
if yesno("Add more dogs?"):
dogs.makeKennel()
print("The kennel now contains")
dogs.display()
while True:
name = input("Which dog do you want? ")
if name == "":
break
breed = dogs.getDog(name)
if breed != None:
print(name, "is a", breed)
#---------------
I hope studying this (and my previous) examples help you understand things better.
Keep at it... It will sink in with a little effort. :-)
I also hope my rather verbose answers give you a little insight about the sort of things you
need to consider when designing your programs.
-=- Larry -=-
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web