Python属性错误:类型对象没有属性

时间:2016-02-18 00:27:56

标签: python oop error-handling

我是Python和编程的新手(从12月开始),并尝试自学一些面向对象的Python并在我的最新项目中出现此错误:

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

我有一个文件要创建" Monster"课程和#34; Goblin"从Monster类扩展的子类。 当我导入两个类时,控制台不会返回错误

>>>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'

2 个答案:

答案 0 :(得分:6)

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

  

AttributeError:类型对象'Goblin'没有属性'color'

将您的行更改为Azog = Goblin()

答案 1 :(得分:3)

当你指定Azog = Goblin时,你没有实例化地精。请改为Azog = Goblin()