gpt4 book ai didi

Python 属性错误 : type object has no attribute

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:16 25 4
gpt4 key购买 nike

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

最佳答案

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

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

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

关于Python 属性错误 : type object has no attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35470510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com