Really Simple Class and Inheritance example in Python
Archive - Originally posted on "The Horse's Mouth" - 2013-03-04 17:15:55 - Graham Ellis
It's so tempting when writing a simple training example to get excited and add lots of features - so that you then end up with an example that's anything but a simple training example!
Here's an example - just about my shortest and simplest ever - that shows a base class, a subclass, inheritance, polymorphism, and a test harness all in a single page of Python:
class pet(object):
def __init__(current,name,age,weight,dailytins):
current.tinnies = dailytins
current.name = name
current.age = age
current.weight = weight * 2.2
def getfood(self,days):
return float(self.tinnies * days)
def __str__(this):
return "Woof says " + this.name
class dog(pet):
pass
class cat(pet):
def __str__(this):
return "Miaow says " + this.name
if __name__ == "__main__":
team = [dog("Gypsy",5,36,3),dog("Billy",3,32,3.5), \
cat("Charlie",15,2,0.33)]
for hound in team:
tins = hound.getfood(7)
print str(hound),"will eat",tins,"tins"
With comments too - and sample output - you'll find that [here].
There's a further example in the course notes, but oen which splits the application into separate files for each class. Whether you want to keep classes together in groups of to separate them depends on if they're going to be:
a) distributed together
b) maintained by the same person
c) updated on the same cycle
d) used with each other in applications
and if you can answer yes, yes, yes and yes ... then you should consider looking after / maintaining them in one unit.
The source code for the split example is [here] for the main test program [here] for the first subclass [here] for the second subclass [here] for the base class
and there's some sample data [here].