Python实例化自定义Animal类触发TypeError:birthType()参数数量错误
报错根本原因
- 核心触发该TypeError的原因是属性的setter方法定义不符合Python语法要求:Python的setter方法必须接收待赋值的内容作为第二个入参,你当前所有setter都只定义了self参数,当执行
self.birthType = birthType这类赋值操作时,Python会自动把self和右侧的赋值内容两个参数传给setter,参数数量不匹配就抛出了该错误。 - 代码还存在其他多处语法&逻辑错误:
- appearence属性的setter拼写错误,多写了一个p,命名为
apppearence,和属性名不匹配,赋值时无法触发对应setter - setter内部赋值时直接引用了未定义的变量,比如
self.__birthType = birthType里的birthType没有作用域来源 __str__方法的最后一个占位符写为{],方括号和大括号混用会触发格式错误- Mammal类的nurseYoung属性的property、setter以及自定义
__str__方法缩进错误,定义在了__init__方法内部,类外部无法访问 - Mammal的nurseYoung setter内部直接给公有属性赋值,会递归调用setter自身,引发无限递归崩溃
- appearence属性的setter拼写错误,多写了一个p,命名为
完整修复代码
class Animal: def __init__(self, birthType="Unknown", appearence="Unknown", blooded="Unknown"): self.birthType = birthType self.appearence = appearence self.blooded = blooded @property def birthType(self): return self.__birthType @birthType.setter def birthType(self, value): self.__birthType = value @property def appearence(self): return self.__appearence @appearence.setter def appearence(self, value): self.__appearence = value @property def blooded(self): return self.__blooded @blooded.setter def blooded(self, value): self.__blooded = value def __str__(self): return "A {} is {} it is {} it is {}".format(type(self).__name__, self.birthType, self.appearence, self.blooded) class Mammal(Animal): def __init__(self, birthType="born alive", appearence="hair or fur", blooded="warm blooded", nurseYoung=True): super().__init__(birthType, appearence, blooded) self.__nurseYoung = nurseYoung @property def nurseYoung(self): return self.__nurseYoung @nurseYoung.setter def nurseYoung(self, value): self.__nurseYoung = value def __str__(self): return super().__str__() + " and it is {} they nurse their young".format(self.nurseYoung) class Reptile(Animal): def __init__(self, birthType="born in an egg or born alive", appearence="dry scales", blooded="cold blooded"): super().__init__(birthType, appearence, blooded) def main(): animal1 = Animal("born alive") print(animal1.birthType) if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者Suhana
相关产品推荐
相关产品推荐

