Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Ashwin Somasundara
Courses Plus Student 2,689 PointsOverriding __init__
Hi Guys, Just wondering how to "override" the _init method. I tried this example here -
import random
COLORS = ['red', 'purple', 'blue', 'magenta', 'black', 'brown']
class Monster:
# these are the monster class defaults
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_hit_points, self.max_hit_points)
self.experience = random.randint(self.min_experience, self.max_experience)
self.color = random.choice(COLORS)
def battlecry(self):
return self.sound.upper()
class Goblin(Monster):
max_hit_points = 3
max_experience = 2
sound = 'squeak'
def __init__(self, *args, **kwargs):
# call base class __init__()
super(Goblin, self).__init__(*args, **kwargs)
color = 'orange' # <-- hard set color
When i try - annaji = Goblin()
I get this error -
Traceback (most recent call last):
File "/example/src/monster.py", line 51, in <module>
annaji = Goblin()
File "/example/src/monster.py", line 47, in __init__
super(Goblin, self).__init__(*args, **kwargs)
TypeError: must be type, not classobj
Whats this all about? Can somebody help!
1 Answer
Evgeny Chuvelev
3,056 PointsHi, Ashwin. Your question was not easy for me. But I found out answer for it. The main thing that u should change in your code is just add object argument in the base Monster class.
import random
COLORS = ['red', 'purple', 'blue', 'magenta', 'black', 'brown']
class Monster(object): # <------- add object argument
min_hit_points = 1
max_hit_points = 1
min_experience = 1
def __init__(self, **kwargs):
self.hit_points = random.randint(self.min_hit_points, self.max_hit_points)
self.experience = random.randint(self.min_experience, self.max_experience)
self.color = random.choice(COLORS)
def battlecry(self):
return self.sound.upper()
class Goblin(Monster):
max_hit_points = 3
max_experience = 2
sound = 'squeak'
def __init__(self, *args, **kwargs):
super(Goblin, self).__init__(*args, **kwargs)
self.color = 'orange' # <----- change color by self
annaji = Goblin()
print annaji.color # 'orange'
This code works for me.