【问题标题】:How to fix attribute error in a class for python如何修复python类中的属性错误
【发布时间】: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


【解决方案1】:

这是一个简单的错字。它的__init__ 不是_init_。 所以应该是:

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()

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 2021-08-14
    • 2021-06-05
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    相关资源
    最近更新 更多