Python help can't figure out why unit test is failing
Hi I am new to python and I am having an issue figuring out what's wrong with my code and why the unit test is failing? Below is the code, unit test and error message when running the test:
legs = []
stomach = []
class Centipede(object):
def __init__(self):
def __str__(self):
return ','.join(self.stomach)
def __call__(self,*args):
[self.stomach.append(arg) for arg in args]
#self.stomach.append(args)
def __repr__(self):
return ','.join(self.legs)
def __setattr__(self, key, value):
print("setting %s to %s" % (key, repr(value)))
if key in ([]):
self.legs.append(key)
#self.__dict__[key] = value
object.__setattr__(self, key,value)
Unit test code
import unittest
from centipede import Centipede
class TestBug(unittest.TestCase):
def test_stomach(self):
ralph = Centipede()
ralph('chocolate')
ralph('bbq')
ralph('cookies')
ralph('salad')
self.assertEquals(ralph.__str__(), 'cho开发者_StackOverflow社区colate,bbq,cookies,salad')
def test_legs(self):
ralph = Centipede()
ralph.friends = ['Steve', 'Daniel', 'Guido']
ralph.favorite_show = "Monty Python's Flying Circus"
ralph.age = '31'
self.assertEquals(ralph.__repr__(),'<friends,favorite_show,age>' )
if __name__ == "__main__":
unittest.main()
error message generated when running the test:
AttributeError: 'Centipede' object has no attribute 'legs'
AttributeError: 'Centipede' object has no attribute 'stomach'
Move the legs and stomach into the Centipede. (I have always wanted to say that :))
class Centipede(object):
def init(self):
self.stomach=[]
self.legs=[]
self.legs is never set before you use it. Are you sure you don't mean just "legs" without the "self" part since you have a global variable called legs that you're not using?
You have declared legs and stomach outside of the class - ralph doesn't know that they are supposed to belong to him.
Putting legs and stomach after the class
line and indenting them the same amount as __init__
should start moving you forward.
精彩评论