Python 属性错误:类型对象没有属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35470510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Attribute Error: type object has no attribute
提问by Frank Hauffe
I am new to Python and programming in general and try to teach myself some Object-Oriented Python and got this error on my lattest project:
我是 Python 和编程的新手,我尝试自学一些面向对象的 Python,但在我的最新项目中遇到了这个错误:
AttributeError: type object 'Goblin' has no attribute 'color'
I have a file to create "Monster" classes and a "Goblin" subclass that extends from the Monster class. When I import both classes the console returns no error
我有一个文件来创建“Monster”类和一个从 Monster 类扩展的“Goblin”子类。当我导入两个类时,控制台没有返回错误
>>>from monster import Goblin
>>>
Even creating an instance works without problems:
即使创建一个实例也没有问题:
>>>Azog = Goblin
>>>
But when I call an attribute of my Goblin class then the console returns the error on top and I don't figure out why. Here is the complete code:
但是当我调用我的 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'
采纳答案by Sebastian Hoffmann
You are not creating an instance, but instead referencing the class Goblin
itself as indicated by the error:
您不是在创建实例,而是Goblin
按照错误指示引用类本身:
AttributeError: typeobject 'Goblin' has no attribute 'color'
AttributeError:类型对象 'Goblin' 没有属性 'color'
Change your line to Azog = Goblin()
将您的线路更改为 Azog = Goblin()
回答by Andy Brown
When you assign Azog = Goblin
, you aren't instantiating a Goblin. Try Azog = Goblin()
instead.
当你赋值时Azog = Goblin
,你不是在实例化一个 Goblin。试试吧Azog = Goblin()
。