'Python Attribute Error: type object has no attribute
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'
Solution 1:[1]
When you assign Azog = Goblin, you aren't instantiating a Goblin. Try Azog = Goblin() instead.
Solution 2:[2]
In
def __init__(self, **kwargs):
self.hit_points = random.randint(self.min_hitpoints, self.max_hit_points)
Switch self.min_hitpoints to self.min_hit_points
and of course do: Azog = Goblin()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andy Brown |
| Solution 2 | Robson |
