Python ch4
Python ch4
PROGRAMMING
LESSON
Abstraction & Inheritance
TABLE OF CONTENTS
01
inheritance
02
Abstraction
What is Inheritance?
The method of inheriting the properties of parent class
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname()
02
Create a Child Class
Create a class named Student, which will inherit the
properties and methods from the Person class:
class Student(Person):
Pass
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
Example of properties :
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
04
Add the super() function
Python also has a super() function that will make the child
class inherit all the methods and properties from its parent:
class Student(Person):
super().__init__(fname, lname)
By using the super() function, you do not
have to use the name of the parent
element, it will automatically inherit the
methods and properties from its parent.
05
Add Properties & Methods
Add a property called graduationyear to the Student
class:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
Add a method called welcome to the Student class:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname,
self.lastname, "to the class of",
self.graduationyear)
EXERCISE
# Question 3
def view(self ):
return ("Book Title: " , self.Title , "Book Author: " , self.Author, "Book Price: " , self.Price)
# Question 4
MyBook = Book("Python Crash Course" , "Eric Matthes" , "23 $")
print( MyBook.view())
# La sortie est : ('Book Title: ', 'Python Crash Course', 'Book Author: ', 'Eric Matthes', 'Book Price: ', '23 $')
What is Abstraction?
Abstraction in python is defined as a process of
handling complexity by hiding unnecessary
information from the user. This is one of the core
concepts of object-oriented programming (OOP)
languages. That enables the user to implement
even more complex logic on top of the provided
abstraction without understanding or even
thinking about all the hidden
background/back-end complexity.
Abstraction Classes
Python provides the abc module to use the abstraction in the Python program. Let's see the following
syntax.
Syntax
Unlike the other high-level language, Python doesn't provide the abstract class itself. We need to import the abc
module, which provides the base for defining Abstract Base classes (ABC). The ABC works by decorating methods of
the base class as abstract.
AbstractionClasses
1. # abstract base class work
1. t= Tesla ()
2. from abc import ABC, abstractmethod
2. t.mileage()
3. class Car(ABC):
3.
4. def mileage(self):
4. r = Renault()
5. pass
5. r.mileage()
6.
7. class Tesla(Car): 6.