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

2024-04-19 13:35:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python和编程还不太熟悉,我试着自学一些面向对象的Python,在lattest项目中出现了以下错误:

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'

Tags: importself错误randomminmaxpointsclass
2条回答

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

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

将行改为Azog = Goblin()

当您分配Azog = Goblin时,您不是在实例化一个Goblin。改为尝试Azog = Goblin()

相关问题 更多 >