本文介绍了Python属性错误:type对象没有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很习惯Python和编程(从12月起),并尝试教自己一些面向对象的Python,并在我的lattest项目中得到这个错误:

  AttributeError:type object'Goblin'没有属性'color'

我有一个文件来创建怪物类和一个怪物子类,从怪物类扩展。
当我导入这两个类时,控制台不返回错误

 >>从怪物导入Goblin 
>>>>

即使创建一个实例也没有问题:

 >>>> Azog = Goblin 
>>>

但是当我调用我的Goblin类的属性时,控制台返回上面的错误,不明白为什么。
这是完整的代码:

  import random 

COLORS = ['yellow' ,'red','blue','green']


class怪物:
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)

为key,value in kwargs.items():
setattr(self,key,value)

def warcry(self):
return self.sound。 $($)


class Goblin(Monster):
max_hit_points = 3
max_experience = 2
sound ='squiek'


解决方案

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

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


I am new to Python and programming in general (since December) and try to teach myself some Object-Oriented Python and got this error on my lattest project:

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

>>>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:

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'
解决方案

You are not creating an instance, but instead referencing the class Goblin itself as indicated by the error:

Change your line to Azog = Goblin()

这篇关于Python属性错误:type对象没有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 10:24