如何修复python类中的属性错误
我不知道如何修复每当我尝试在不使用全局变量的情况下创建类时发生的属性错误。错误是 AttributeError:“动物”对象没有“栖息地”属性 错误发生在第6行:如何修复python类中的属性错误,python,class,attributes,self,Python,Class,Attributes,Self,我不知道如何修复每当我尝试在不使用全局变量的情况下创建类时发生的属性错误。错误是 AttributeError:“动物”对象没有“栖息地”属性 错误发生在第6行: class Animal: def _init_(self): self.habitat = 'Jungle' self.diet = 'carnivore' def speak(self): print(f"I live in the {self.habitat} an
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()
这是一个简单的打字错误。它的
\uuu init\uuu
不是\uu init\uuu
。
因此,它应该是:
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()
双下划线表示
\uuuu init\uuuuuu
也许以打字错误结束这个问题不是最好的选择。这可能是一个简单的解决方案,但其他人可能会在将来遇到同样的问题,这并不是显而易见的,让您的.speak()
方法打印而不是返回字符串可能不是最好的设计选择。