π Inheritance
Contents
π Inheritance#
Inheritance allows one class to inherit properties from another class.
It is usually referred to as child and parent classes.
It allows you to better represent real-world relationships.
Code can become much more reusable.
It is transitive meaning that if Class B inherits from Class A then subclasses of Class B would also inherit from Class A.
Inheritance Example#
Syntax
Class BaseClass: {Body} Class DerivedClass(BaseClass): {Body}
Step 1: Create a parent class with a method#
Create a parent class named
Person
that defines aname
andage
Add a Class method that prints the name and title
class Person:
# Constructor
def __init__(self, name, age):
self.name = name
self.age = age
# To check if this person is an employee
def Display(self):
print(self.name, self.age)
Testing#
jedi = Person("Darth Vader", 56)
jedi.Display()
Step 2: Creating a Child Class;#
Create a child class of
Person
,Jedi
that has a methodPrint
that printsJedi's use the force
class Jedi(Person):
def Print(self):
print("Jedi's use the force")
Testing#
# instantiate the parent class
jedi_info = Jedi("Darth Vader", 56)
# calls the parent class
jedi_info.Display()
# calls the child class
jedi_info.Print()
Step 3: Adding Inheritance#
Starting with the base Class
Person
we can add a method togetName
that returns thename
We can add a method
isAlliance
that establishes if the person is part of the Rebel Alliance, the default should beFalse
We can add a inherited child class
Alliance
that changesisAlliance
toTrue
class Person:
# Constructor
def __init__(self, name, age):
self.name = name
self.age = age
# Function that gets the name
def getName(self):
return self.name
# Function that returns if the person is part of the alliance
def isAlliance(self):
return False
# Inherited child class
class Alliance(Person):
# This will change the isAlliance class to True
def isAlliance(self):
return True
Test#
darth_vader = Person("Darth Vader", 56)
print(darth_vader.getName(), darth_vader.isAlliance())
luke_skywalker = Alliance("Luke Skywalker", 21)
print(luke_skywalker.getName(), luke_skywalker.isAlliance())