[英]Problems with inheriting the correct property with the child class in python
我需要讓子 class 從父 class 繼承。 我繼續得到“TypeError: init ()缺少1個必需的位置參數:'species'”或者名稱經常被分配給名稱並且名稱繼續返回為無。
import unittest
import time
class Mammal:
""" A Mammal class to further populate our animal kingdom """
def __init__(self, species, name):
""" mammal constructor can initialize class attributes """
self.species = species
self.name = None
def eat(self, food):
""" a method that will 'eat' in O(n) time """
i = food
print(self.name, "the", self.species, "is about to eat")
while i >= 1:
time.sleep(0.1)
i = i // 2
print(" ", self.name, "is done eating!")
def makeNoise(self):
""" a method that should be implemented by children classes """
raise NotImplementedError("this method should be implemented by child class")
在此處添加您需要/想要的任何其他基礎 CLASS 方法
def __eq__(self, object):
return isinstance(object, Mammal) and object.species == self.species
需要完成以下兩個課程,並且您需要替換/刪除下面顯示的所有省略號
class Hippo(Mammal):
def __init__(self, name, species):
self.name = name
self.species = 'hippo'
def getName(self):
return self.name
def setName(self, h):
self.name = h
def makeNoise(self):
return 'grunting'
class Elephant(Mammal):
def __init__(self, name, species):
self.name = name
self.species = 'elephant'
def getName(self):
return self.name
def setName(self, e):
self.name = e
def makeNoise(self):
return 'trumpeting'
class TestMammals(unittest.TestCase):
""" a class that is derived from TestCase to allow for unit tests to run """
def testInheritance(self):
""" confirm that Elephant and Hippo are children classes of Mammal """
self.assertTrue(issubclass(Elephant, Mammal) and issubclass(Hippo, Mammal))
def testEqOperator(self):
hip1 = Hippo('John')
hip2 = Hippo('Arnold')
self.assertEqual(hip1, hip2)
def main():
""" a 'main' function to keep program clean and organized """
print("-------------------- start main --------------------")
e = Elephant("Ellie")
h = Hippo("Henry")
if(e == h):
print(e.getName(), "and", h.getName(), "are of the same species")
else:
print(e.getName(), "and", h.getName(), "are *not* of the same species")
def listenToMammal(Mammal):
print(Mammal.makeNoise())
listenToMammal(e)
listenToMammal(h)
e.eat(100)
print("--------------------- end main ---------------------")
if __name__ == "__main__":
main()
unittest.main()
在此處輸入圖像描述這是 output 的外觀,但我很困惑
您仍在定義Hippo.__init__
以獲取 2 arguments,即使您忽略了物種參數。 你可以放下那個。 您還應該使用Mammal.__init__
而不是自己設置屬性。
class Hippo(Mammal):
def __init__(self, name):
super().__init__(self, name, species='hippo')
def getName(self):
return self.name
def setName(self, h):
self.name = h
def makeNoise(self):
return 'grunting'
getName
和setName
不是必需的; 您可以直接訪問name
屬性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.