Inheritance
Date: February 4th 2016
Last updated: February 7th 2016
Inheritance is used to assign functions of one class to another. Inheritance is used for object associations with an "is a" relationship.
For example, dog is an animal, cat is an animal and person is an addressholder. In each of these cases, the subclass (e.g. dog) inherits the methods of a parent class (e.g. animal). Then, each subclass can be extended with specific functionality. For example, the dog subclass may have a method to bark and a cat to meow. Yet both inherit from the animal parent class to make a sound in the first place.
Inherit from data types:
class MyClass(list):
pass
mylist = MyClass()
mylist
#returns an empty list: []
Example:
class Animal(object):
"""
Parent class specifying if an animal makes a sound
"""
def vocalise(self):
return True
class Dog(Animal):
"""
Example inheritance for Dog subclass to vocalise as a bark
"""
def gaurd(self):
# use Animal method
if self.vocalise():
return 'bark bark bark'
class Cat(Animal):
"""
Example inheritance for the Cat subclass to be annoying
"""
def be_annoying(self):
if self.vocalise():
return 'meeooooow'