How to print nicely?
I have two classes:
class Dog(object):
def __init__(self, name):
self.name = name
class Toy(object):
def play(self):
print "Squeak!"
I need to come up with a method called play(self, toy, n) for class Dog. It prints "Yip! " (with a space) followed by the output from toy.play on the same line. This happens n times, with the n outputs on separate lines. If n is negative, it is the same as if it were 0.
What I did is
def play(self, toy, n):
count = 1
if n > 0:
while count <= n:
print "Yip! %s " % Toy().play()
count += 1
else:
print None
However, when I call Dog('big').play(toy, 3) or whatever n is, it shows that Squeak! Yip! None Squeak! Yip! None Squ开发者_如何学运维eak! Yip! None I don't know what's wrong. Squeal! and Yip! should suppose to be at the same line while there are at separate now and there order should be opposite. And why there is a None? Can anyone please help me out?
In your example call, Dog('big').play(0)
, you are not passing the toy
argument -- that's what it's complaining about! Pass a toy argument before n
and that will be better.
Then you can start addressing the bugs in your play
implementation: why are you making a new toy rather than use the argument, why are you printing 'None'
when that's not part of the specs, how you're uselessly printing the return value of the Toy.play
method (which returns None
, implicitly) rather than working along with the fact that the latter method is print
ing something, and never incrementing count
and so ending up in infinite loops.
(four serious bugs in eight lines plus one in the call just has to be some sort of a record, I believe;-).
BTW, homework is normally tagged with the tag homework
, not exercise
. (And, there's a further bug in your Q's title, as no classmethod is actually around, just a good old plain and perfectly normal instance method).
The first thing I see wrong is the you are attempting to call the class 'Toy' instead of the variable representing the instance 'toy' passed to you 'play' method. I don't believe you can instantiate a class and call one of its methods at the same time which is what 'Toy().play()' is trying to do. The other is that I'm not quite sure I understand what you are trying to do with the design of your classes. Here is how I would implement the classes and then use them to get your desired behavior.
class Toy(object):
def play(self):
return "Squeak!"
class Dog(object):
speak = 'Yip! %s'
def __init__(self, name, toy):
self.name = name
self.toy = toy
def play(self,n):
if n > 0:
for each in range(n):
print(self.speak % self.toy.play())
else:
print(None)
and here is how I would use it
Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from toy import Toy, Dog
>>> spike = Dog("Spike",Toy())
>>> spike.play(3)
Yip! Squeak!
Yip! Squeak!
Yip! Squeak!
>>>
精彩评论