Python Attribute Error: type object has no attribu

2020-02-06 03:38发布

问题:

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:

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'

回答1:

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

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

Change your line to Azog = Goblin()



回答2:

When you assign Azog = Goblin, you aren't instantiating a Goblin. Try Azog = Goblin() instead.