【发布时间】:2020-01-04 17:20:49
【问题描述】:
我不知道如何解决这个在我尝试在不使用全局变量的情况下创建类时发生的属性错误。错误说
AttributeError: 'Animal' 对象没有属性 'habitat'。
第6行出现错误:
class Animal:
def _init_(self):
self.habitat = 'Jungle'
self.diet = 'carnivore'
def speak(self):
print(f"I live in the {self.habitat} and eat {self.diet}")
animal_1 = Animal()
animal_1.speak()
【问题讨论】:
-
__init__的双下划线 -
也许以拼写错误结束这个问题并不是最好的选择。这可能是一个简单的修复,但其他人将来可能会遇到同样的问题,而且不是很明显
-
顺便说一句,让你的
.speak()方法打印而不是返回一个字符串可能不是最好的设计选择。
标签: python class attributes self