【问题标题】:Python Attribute Error: type object has no attributePython 属性错误:类型对象没有属性
【发布时间】:2016-02-18 00:27:55
【问题描述】:

我是 Python 和一般编程的新手,并尝试自学一些面向对象的 Python,并在我的最新项目中遇到此错误:

AttributeError: type object 'Goblin' has no attribute 'color'

我有一个文件来创建“Monster”类和从 Monster 类扩展的“Goblin”子类。 当我导入两个类时,控制台不返回错误

>>>from monster import Goblin
>>>

即使创建实例也没有问题:

>>>Azog = Goblin
>>>

但是当我调用我的 Goblin 类的属性时,控制台会在顶部返回错误,我不知道为什么。 完整代码如下:

import random

COLORS = ['yellow','red','blue','green']


class Monster:
    min_hit_points = 1
    max_hit_points = 1
    min_experience = 1
    max_experience = 1
    weapon = 'sword'
    sound = 'roar'

    def __init__(self, **kwargs):
        self.hit_points = random.randint(self.min_hitpoints, self.max_hit_points)
        self.experience = random.randint(self.min_experience,  self.max_experience)
        self.color = random.choice(COLORS)

        for key,value in kwargs.items():
            setattr(self, key, value)

    def battlecry(self):
        return self.sound.upper()


class Goblin(Monster):
    max_hit_points = 3
    max_experience = 2
    sound = 'squiek'

【问题讨论】:

  • >>>Azog = Goblin 应该是 >> Azog = Goblin() 你当前没有实例化你的类。

标签: python oop error-handling


【解决方案1】:

您不是在创建实例,而是引用类 Goblin 本身,如错误所示:

AttributeError: type object 'Goblin' has no attribute 'color'

将您的线路改为Azog = Goblin()

【讨论】:

    【解决方案2】:

    当您分配Azog = Goblin 时,您并没有实例化一个地精。请改用Azog = Goblin()

    【讨论】:

      【解决方案3】:

       def __init__(self, **kwargs):
              self.hit_points = random.randint(self.min_hitpoints, self.max_hit_points)
      

      self.min_hitpoints 切换为self.min_hit_points

      当然可以:Azog = Goblin()

      【讨论】:

        猜你喜欢
        • 2010-12-23
        • 2014-05-14
        • 1970-01-01
        • 2018-12-07
        • 2017-11-12
        • 2014-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多