You definitely do need to use __init__
here. __init__
allows you to set attributes for a class that can then be used in functions or called on externally. It runs when a class is first created, so it's often used to set up the values that a class needs to run. Here's a very simple example:
class Player:
def __init__(self, name):
self.name = name
def print_name(self):
print("My name is " + self.name)
player1 = Player("Mario")
player2 = Player("Luigi")
print(player1.name)
# Mario
player2.print_name()
# My name is Luigi
You can see how this uses the self.name
set up you had, but you don't need to pass name
into the functions each time. Instead, when the class is created, you give it a name
value that gets stored in the class to be called in later. (note that you don't technically need to assign these values with __init__
, you could just do player1.name = "Mario"
but that's much less neat than using __init__
).
So in your case, let's set up your first class. I'd start by actually naming the class Player
, not just calling it Parent
and then giving it a name attribute that gets constantly overwritten. Then lives = 3
should also be in __init__
as putting it where you have it makes it a class attribute. Those are more commonly used for constants, or values shared across the whole class. __init__
is where you put the values that each individual instance of the class should have thir own value for:
class Player:
def __init__(self, name):
self.name = name
self.lives = 3
#display player running
def run(self):
print "%s is running." % self.name
#player will start to jump against enemy
def jump(self):
print "%s jumps over enemy. TOINK TOINK" % self.name
#player will start to grow
def grow(self):
print "%s starting to Grow" % self.name
Now you can see that you don't need to pass in name
any more because it's part of the class. It can easily reference it with self.name
instead. Also, I don't think you need separate classes for Mario and Luigi, since the only difference is that their function prints something different. Instead you could pass name
and skill
as two parameters and use them in the special_skill
function:
class Player:
def __init__(self, name, skill):
self.name = name
self.skill = skill
lives = 3
def special_skill(self):
print "%s used his %s" % (self.name, self.skill)
Some other notes. You should look into docstrings. They make functions clearer and easier to read. You have comments on each function already, so it's good to turn them into docstrings.
Instead of using %
to format, use str.format
which is the new style for formatting. It's cleaner and easier, and has other advantages for down the line. For example you could turn
print "%s used his %s" % (self.name, self.skill)
into
print "{} used his {}".format(self.name, self.skill)