Classes - Inheritance
In the previous tutorial we created a class of animals. If we think about it, animals might be a far too general class. There are different kinds of animals - dogs, cats, butterflies. Infect we can classify animals to mammals, reptiles etc.
Python has an Inheritance feature.
In python we can create a new class based on another one. The new class gets all the methods of its parent unless we decide to modify or add methods.
Child - is the new class that inherits the features.
Parent - is the base class, from which the new class inherits the features.
Watch the example:
#Animal class
class Animal(object):
def __init__(self, name, age, hunger_level=9):
self.name = name
self.age = age
self._hunger_level = hunger_level
def run(self):
if self._hunger_level == 10:
print("Animal is too hungry to run")
else:
self._hunger_level += 1
def eat(self):
if self._hunger_level == 0:
print("Animal can't eat")
else:
self._hunger_level -= 1
def say_age(self):
print(self.age)
def say_hunger(self):
print(self.hunger_level)
#Create a child class - cats
class Cat(Animal):
def __init__(self, name, age, hunger_level=9):
self.name = name
self.age = age
self._hunger_level = hunger_level
#Create a cat object
my_cat = Cat("Apollo", 5)
#We can use all the methods of Animal since Cat inherits them
my_cat.say_age()
my_cat.run()
my_cat.run()
my_cat.eat()
Overide Methods
We can overide methods and add new methods:
#Animal class
class Animal(object):
def __init__(self, name, age, hunger_level=6):
self.name = name
self.age = age
self._hunger_level = hunger_level
def run(self):
if self._hunger_level == 10:
print("Animal is too hungry to run")
else:
self._hunger_level += 1
def eat(self):
if self._hunger_level == 0:
print("Animal can't eat")
else:
self._hunger_level -= 1
def say_age(self):
print(self.age)
def say_hunger(self):
print(self.hunger_level)
#Create a child class - cats
class Cat(Animal):
def __init__(self, name, age, hunger_level=7):
self.name = name
self.age = age
self._hunger_level = hunger_level
#overide the run() method
def run(self):
if self._hunger_level == 8:
print(self.name, "is too hungry to run")
else:
self._hunger_level += 1
def say_name(self):
print(self.name)
#Create a cat object
my_cat = Cat("Apollo", 5)
#use methods
my_cat.say_age()
my_cat.say_name()
my_cat.run()
my_cat.run()
my_cat.run()
my_cat.eat()
Exercise
Create a parent class and a child class.
When you create the child class overide some of the methods.
#Write your code here: