![](/img/trans.png)
[英]Python help can't figure out why this function is failing to call inside the function call
[英]Python help can't figure out why unit test is failing
嗨,我是python新手,我在弄清楚我的代碼出什么問題以及單元測試失敗的原因時遇到了問題? 以下是運行測試時的代碼,單元測試和錯誤消息:
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)
單元測試代碼
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__(), 'chocolate,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()
運行測試時生成錯誤消息:
AttributeError: 'Centipede' object has no attribute 'legs'
AttributeError: 'Centipede' object has no attribute 'stomach'
將腿部和腹部移到the中。 (我一直想這樣說:)
class Centipede(object):
def init(self):
self.stomach=[]
self.legs=[]
在使用self.legs之前,請不要對其進行設置。 您確定沒有包含“ self”部分的“ legs”不是指“ legs”,因為您有一個未使用的全局變量稱為legs?
您已經在課外宣布了腿和肚子-拉爾夫不知道他們應該屬於他。
將腿和肚子放到class
線后,並與__init__
縮進相同的距離,應該會開始使您前進。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.