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

发布于 2021-01-29 17:34:21

我是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'
关注者
0
被浏览
223
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

    AttributeError: 类型 对象“地精”没有属性“颜色”

    将行更改为 Azog = Goblin()



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看