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