How to Use Inheritance in Python - CNDRO.LLC
3156
post-template-default,single,single-post,postid-3156,single-format-standard,wp-custom-logo,theme-bridge,bridge-core-2.9.4,woocommerce-no-js,tribe-no-js,ehf-template-bridge,ehf-stylesheet-bridge-child,qode-page-transition-enabled,ajax_fade,page_not_loaded,,qode-title-hidden,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,columns-4,qode-child-theme-ver-1.0.0,qode-theme-ver-27.8,qode-theme-bridge,qode_header_in_grid,wpb-js-composer js-comp-ver-6.7.0,vc_responsive,elementor-default,elementor-kit-2634

How to Use Inheritance in Python

Photo by Nubelson Fernandes on Unsplash

Single Inheritance

1class Person:
2 def __init__(self, firstName, lastName):
3 self.fname=firstName
4 self.lname=lastName
5
6 def printname(self):
7 print(self.fname, self.lname)
8
9
10class Student(Person):
11 pass
12user = Student("Mike", "Johnson")
13user.printname()
14#Result
15Mike Johnson

Multiple Inheritance

1# Base class1 
2class Name: 
3    PName = "" 
4    def Name(self): 
5        print(self.PName) 
6  
7# Base class2 
8class Age: 
9    Agevalue = "" 
10    def Age(self): 
11        print(self.Agevalue) 
12  
13# Derived class 
14class BData(Name, Age): 
15    def userData(self): 
16        print("Name :", self.PName) 
17        print("Age :", self.Agevalue) 
18 
19the_data = BData() 
20the_data.PName = "Grace" 
21the_data.Agevalue = "15" 
22the_data.userData()  
23
1#Result 
2Name : Grace 
3Age : 15

We have another example below, where we have the Base class

‘Intern’, ‘FullWorker’

 and also a child class

TeamLeader

 which inherits the 2 base class (

‘Intern’, ‘FullWorker’

) and gets to access all properties and elements of each of those classes.

2# Parent class 1 
3class Intern(object): 
4    def __init__(self, name): 
5        self.name = name  
6   
7# Parent class 2 
8class FullWorker(object): 
9    def __init__(self, salary, jobtitle):  
10        self.jobtitle = jobtitle  
11        self.salary = salary 
12   
13# Deriving a child class from the two parent classes 
14class TeamLeader(Intern, FullWorker): 
15    def __init__(self, name, jobtitle, salary, experience):  
16        self.experience = experience 
17        Intern.__init__(self, name)  
18        FullWorker.__init__(self, salary, jobtitle) 
19        print("Name: {}, Pay: {}, Exp: {}".format(self.name, self.salary, self.experience)) 
20 
21the_teamlead = TeamLeader('Bill','Data Engineer', 300000,  4)


1#Result 
2Name: Bill, Pay: 300000, Exp: 4

 

 Thanks for reading this article. Feel free to drop your comments and questions in the comments section below.
No Comments

Post A Comment