What are the proper ways of adding a common set of method/properties to subclasses derived from the same class?
Let’s say that these are my classes that I need for a videogame based on animals (it’s just an example, I am not really writing a game but the idea is the same)
class Animal():
def __init(self, numlegs):
self.numlegs = numlegs
class Dog(Animal):
def __init(self, numlegs):
Animal.__init__(self, numlegs)
def bark(self):
print "Arf!"
class Cat(Animal):
def __init(self, numlegs):
Animal.__init__(self, numlegs)
def playwithmouse(self):
print "It's fun!"
class Duck(Animal):
def __init(self, numlegs):
Animal.__init__(self, numlegs)
def fly(self):
print "Weee!"
At a certain point in the game Dog and Duck can be weaponized, and they need to have the same methods: fire(), reload() and properties: ammocount.
I don’t think it would be correct to add them in the Animal() class, because they will be needed in a completely different part of the game.
What would be the correct approach to add them?
update
I wanted to add that the expected result is some kind of
Animal – Weapon Hybrid Class like
class BurtalDuck(Duck):
fire(): #<- this is somehow added to Duck
print "ratatatatat!"
What I get from the answers is that if I need the whole set of “weapons/ammos” I can use multiclassing, otherwise composition is the way to go.
One possibility: don’t add them to the classes at all. Create a “weapon” class that contains all of the info regarding how weapons work, and add an instance of that class to the objects that can be weapons.
Of course, this means a bit rethinking of your architecture, but it’s a nice concept to think about. This idea typically goes by the name “component-based”. Google for “component-based game objects” and try to find some blog posts/presentations that describe the idea.