I am trying to learn a little more about Classes in Python, and am writing a program to help with this. I have defined my Parent Class and Child class as follows:
class Character():
'Common base class for all characters'
def __init__(self):
self.attack = 1
self.defence = 1
self.strength = 1
def setAttack(self, attack):
self.attack = attack
def setDefence(self, defence):
self.defence = defence
def setStrength(self, strength):
self.strength = strength
class Enemy(Character):
'Enemy Class'
def __init__(self):
self.setAttack(random.randint(5,20))
self.setDefence(random.randint(5,20))
self.setStrength(random.randint(5,20))
This means I can define an enemy with the line
enemy1 = Enemy()
My view is I can then copy the Enemy class with different random values to create different types of enemy. i.e. Create a BiggerEnemy Class the same as above but with different random values.
While this code above works, all the text books and documentation I have read indicate I should structure my code as such:
class Character():
'Common base class for all characters'
def __init__(self, attack, defence, strength):
self.attack = attack
self.defence = defence
self.strength = strength
def setAttack(self, attack):
self.attack = attack
def setDefence(self, defence):
self.defence = defence
def setStrength(self, strength):
self.strength = strength
class Enemy(Character):
'Enemy Class'
def __init__(self, attack,defence,strength):
Character.__init__(self, attack, defence, strength)
self.attack = attack
self.defence = defence
self.strength = strength
self.setAttack(random.randint(5,20))
self.setDefence(random.randint(5,20))
self.setStrength(random.randint(5,20))
Which is fine, but this means I would have to declare what goes into the Child class by setting Attack, Defence and Strength in order to create the enemy
enemy1 = Enemy(10,10,10)
I am wondering if my method is incorrect, and if I am missing something about how classes work. All the documentation I have read seems to point to the fact I am wrong with my code, but the alternative seems to negate the need for the Child Class. Hence my first posting on stackoverflow.