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
Squeak!
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 thetoyargument — that’s what it’s complaining about! Pass a toy argument beforenand that will be better.Then you can start addressing the bugs in your
playimplementation: 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 theToy.playmethod (which returnsNone, implicitly) rather than working along with the fact that the latter method isprinting something, and never incrementingcountand 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, notexercise. (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).