CHAPTER 8 - PYTHON INHERITANCE



AD

Python inheritance for a class

We can create a new child class that inherits the properties of the parent class. We can add new, additional properties to the child class.

Below the child class is Developer, and we are adding a class of variable called language. Notice the code to develop the child class is a little different. Carefully compare the child Developer to the parent Employee above it. The new term is super, which repeats the variables from Employee. The variable language is added.

If we add the method super().getinfo() to the child, we have not done anything special. The child method is a repeat of the parent method and does not include language. We would have to redefine a new method to include language.

#Inheritance

class Employee:
  def __init__(self, name, email, job):
   self.name = name
   self.email = email
   self.job = job

  def getinfo(self):
   return '{} {} {}'.format(self.name, self.email, self.job)

class Developer (Employee): #Child class to create language variable
  def __init__(self, name, email, job, language):
   super().__init__(name, email, job)
   self.language = language
   super().getinfo()     #getinfo() is not a new method of Developer
           #it is a repeat of the method in Employee
employee1 = Developer("Steve", "steve@dot.com", "developer", "Basic")
print(employee1.email)
print(employee1.language)
print(employee1.getinfo())       #Prints out info from Employee class
         #Does not print out language


#Output
# steve@dot.com
# Basic
# Steve steve@dot.com developer

theSurfDragon.com


Python Navigation

Table of Contents
Ch1-Starting Out
Ch2-Loops
Ch3-If Statements
Ch4-Functions
Ch5-Variable Scope
Ch6-Bubble Sort
Ch7-Intro to OOP
Ch8-Inheritance
Ch9-Plotting
Ch10-Files
Ch11-Print Format
Ch12-Dict-Zip-Comp
Ch13-Slice Arrays