Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

1.4 - OOPS Concepts in Python

Uploaded by

harsheenkaur1811
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

1.4 - OOPS Concepts in Python

Uploaded by

harsheenkaur1811
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

OOPS Concepts in Python

Web Developer-Python 1
Error/ Warning Information Flashback Class Exercise

Web Developer-Python 2
1. Classes and Objects

2. Inheritance and its types

AGENDA 3. Multiple Inheritance

4. Function Overloading

5. Operator Overloading

Web Developer-Python 3
1. Classes and Objects

Web Developer-Python 4
Object-oriented programming

OOP

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “class” and "object“.
Features:
▪ Classes and Objects
▪ Inheritance and its types
▪ Multiple Inheritance
▪ Function Overloading
▪ Operator Overloading

Web Developer-Python 5
Classes and objects

Class
A class in Python is a blueprint or a template for creating objects.
▪ Classes are created by keyword class.
▪ Attributes are the variables that belong to a class.
▪ Attributes are always public and can be accessed using the dot (.) operator. Example - MyClass.MyAttribute

Object

An object in Python is an instance of a class.


▪ State: It is represented by the attributes of an object. It also reflects the properties of an object.
▪ Behavior: It is represented by the methods of an object. It also reflects the response of an object to other
objects.
▪ Identity: It gives a unique name to an object and enables one object to interact with other objects.
Web Developer-Python 6
Classes and objects

Class : Human

Name
Human : object01 Human : object02
Job
Address

Sherlock Holmes Tarzan


Detective Adventurer, Hunter
221B Baker Street Jungle, Africa

Web Developer-Python 7
Classes and objects

Create a class
▪ “class” keyword Class : Human

▪ Syntax

▪ Example

Web Developer-Python 8
Classes and objects

The “pass” keyword in Python is used as a placeholder for future code.

Web Developer-Python 9
Classes and objects

Create an object
▪ Syntex Human : tarzan

▪ Example

▪ Verify object of a particular class

Web Developer-Python 10
Classes and objects

The isinstance() function is used to check if an object (first argument) is an instance or subclass instance of a
class or a tuple of classes (second argument). It returns True if the object is an instance of the class (or of one of
the classes in the tuple), and False otherwise.

Web Developer-Python 11
Classes and objects

▪ The data associated with the objects or instances are called attributes.
▪ The actions that the objects can perform or allow us to perform on them are called methods.

Web Developer-Python 12
Classes and objects

The __init__() function


▪ The __init__() function is called automatically every time the class is being used to create a new object.

The “self” parameter


▪ Instance reference: The self parameter is a reference to the current instance of the class.
▪ Attribute access: It allows access to the attributes and methods of the class within its methods.

Web Developer-Python 13
Classes and objects

It does not have to be named “self”, you can call it whatever you like, but it has to be the first parameter of
any function in the class.

Web Developer-Python 14
Classes and objects

The __str__() Function


▪ The __str__() function controls what should be returned when the class object is represented as a string.
▪ If the __str__() function is not set, the string representation of the object is returned.

Web Developer-Python 15
Classes and objects

Let’s create a function to display information of the human object

Web Developer-Python 16
Classes and objects

Let’s create an object

Web Developer-Python 17
Classes and objects

Create object “tarzan” of human class and display it’s information using display_info() function.

Web Developer-Python 18
Classes and objects

Change the property of object

Web Developer-Python 19
Classes and objects

Delete an object
▪ “del” keyword

▪ Using the “del” keyword delete the “address” property of the “tarzan” object.
Web Developer-Python 20
Classes and objects

Let's create a Car class with the properties - model, brand, fuel_type, and price. And also add two methods: one to
display the car's details and another to calculate the price after applying a discount.

Sample output

Car Details:
Model: Model S
Brand: Tesla
Fuel Type: Electric
Price: $79999

Price after 10% discount: $71999.1

String Representation of Car Object:


Car(Model: Model S, Brand: Tesla, Fuel Type: Electric, Price: $79999)

Web Developer-Python 21
Question?

Web Developer-Python 22
2. Inheritance

Web Developer-Python 23
Inheritance

Inheritance in human

Grandparents

Parents

Child 24
Web Developer-Python
Inheritance

Inheritance in python
Inheritance is a mechanism in OOP that allows a class to inherit attributes and methods from another class.
▪ The class that inherits is called the derived class or child class.
▪ The class being inherited from is called the base class or parent class.

Benefits

▪ Reusability: Reuse existing code, reducing redundancy.


▪ Extensibility: Extend and enhance functionalities.
▪ Maintainability: Easier to manage and update code.

Web Developer-Python 25
Inheritance

Syntax

Here the “ChildClass” inherits from “ParentClass”.

Web Developer-Python 26
Inheritance

Types
1. Single Inheritance

2. Multiple Inheritance

3. Multilevel Inheritance

4. Hierarchical Inheritance

5. Hybrid Inheritance

Web Developer-Python 27
Inheritance

“self” is a reference to the current instance of the class. It is used to access variables and methods
associated with the current object.

Web Developer-Python 28
Inheritance

1. Single inheritance
A derived class inherits from a single base class.

Base class : Animal

Derived class : Dog

Dog class inherits Animal class.


Web Developer-Python 29
Inheritance

2. Multiple inheritance
A derived class inherits from more than one base class.
Base class 01: Flyer Base class 02: Swimmer

Derived class : Duck

Web Developer-Python 30
Inheritance

3. Multilevel inheritance
A derived class inherits from another derived class. Level 0
Base class : Animal

Level 1
Derived class : Mammal

Level 2
Derived class : Dog
Web Developer-Python 31
Inheritance

4. Hierarchical inheritance
Multiple derived classes inherit from a single base class.

Base class :
Animal

Derived class : Fish


Derived class : Dog Derived class : Bird

Web Developer-Python 32
Inheritance

5. Hybrid inheritance
A combination of two or more types of
inheritance.

Animal

Mammal
Swimmer

Fish

Dog
Web Developer-Python 33
Inheritance

The super() function


The __init__() function of “Animal” superclass being initialized using the object of derived class “Dog”.

Web Developer-Python 34
Inheritance

The super() function


▪ The __init__() function of derived class
will no longer inherits the parent's
__init__() function.

▪ Now, object of derived class “Dog”


pointing the __init__() function of its
own.

Web Developer-Python 35
Inheritance

The super() function


Use parent.__init__()

Web Developer-Python 36
Inheritance

The super() function


The super() function will allow child class inherit all the methods and properties from its parent.

Web Developer-Python 37
Inheritance

Disadvantages of inheritance

▪ Increased complexity

▪ Tight coupling

▪ Can lead to the diamond problem in multiple inheritance

Web Developer-Python 38
Inheritance

The "diamond problem" occurs when a class inherits from two classes that have a common ancestor. This
creates a diamond-shaped inheritance hierarchy, leading to ambiguity in method resolution.

Write a program to illustrate the “diamond problem” in the context of python.

Web Developer-Python 39
Inheritance

Create a Python program to manage different types of vehicles. Follow these steps: # Example Usage

1. Create a base class Vehicle with: car = Car("Toyota", "Corolla", 5)


▪ Attributes: brand and model. bike = Bike("Yamaha", "MT-15", "Sports")
▪ Method: display_info() to print the brand and model. car.display_info()
bike.display_info()
2. Create a class Car that inherits from Vehicle with:
▪ An additional attribute: seats. # Expected Output
▪ Override the __init__() method to initialize brand, model and seats.
▪ Override the display_info() method to: Brand: Toyota, Model: Corolla
• Call the display_info() method from Vehicle. Seats: 5
• Print the number of seats. Brand: Yamaha, Model: MT-15
Type: Sports
3. Create a class Bike that inherits from Vehicle with:
▪ An additional attribute: type_bike.
▪ Override the __init__() method to initialize brand, model and type_bike.
▪ Override the display_info() method to:
• Call the display_info() method from Vehicle.
• Print the type of bike.

4. CreateWeb
instances of Car and Bike and call their display_info() methods.
Developer-Python 40
Question?

Web Developer-Python 41
4. Function Overloading

Web Developer-Python 42
Function overloading

Definition
Two or more functions have the same name but
▪ different numbers of parameters
▪ or different types of parameters
▪ or both.
This is called function overloading.

Python does not support traditional function overloading. However, a similar effect can be achieved using –
▪ default arguments
▪ variable-length arguments
▪ conditional logic inside methods.

Web Developer-Python 43
Function overloading

Need of function overloading?


Two or more functions in the same scope
with same names will cause error.

Here which function will be called by


product(4, 5) ?
a) product(a, b)
b) product(a, b, c)

Web Developer-Python 44
Function overloading

Without function overloading

To perform the same task there are two different methods – speak() and speak_with_sound()
Web Developer-Python 45
Function overloading

With function overloading


Using the concept of function overloading with default arguments and conditional logic it can be simplified

Web Developer-Python 46
Function overloading

Overload inherited function

Web Developer-Python 47
Function overloading

What is inheritance?

Inheritance in OOP allows a new class (called a “child class” or "subclass" or "derived class") is created by inheriting the
properties and behaviors (methods) of an existing class (called a "base class" or "superclass“ or “parent class”).

Web Developer-Python 48
Function overloading

Multiple dispatch decorator


This decorator allows you to define multiple implementations of a function or method based on the types and
number of arguments passed to it.

Install Multiple Dispatch Decorator:

pip install multipledispatch

Web Developer-Python 49
Function overloading

Multiple dispatch decorator


Three implementations of the product() function are defined
using the @dispatch decorator.

▪ The first implementation is for two int arguments.


▪ The second implementation is for three int arguments.
▪ The third implementation is for three float arguments.

What will be the output of this code?


Web Developer-Python 50
Function overloading

Benefits of function overloading


▪ Enhanced Readability: The method name product() is intuitive and clearly indicates its purpose. With
overloading, we do not need to remember multiple method names for similar actions.

▪ Code Reusability: Instead of creating multiple methods with different names, we reuse the same method
name to handle various scenarios.

▪ Flexibility and Ease of Use: The product() method can be called with or without an argument, making it
flexible and easy to use.

Web Developer-Python 51
Function overloading

Implement a class hierarchy with “Person” as the base class and “Student” as # Example Usage
the derived class. The Student class should have a method to add skills. Use
function overloading to handle the following cases: student = Student("John Doe", 20)
student.add_skill("Python")
▪ Objective student.add_skill(["Java", "C++"])
student.add_skill({"Data Analysis": "Advanced",
1. Add a single skill: Takes one string argument (skill) and adds it to the "Machine Learning": "Intermediate"})
student's skill set. print(student.skills)
2. Add multiple skills: Takes a list of strings (skills) and adds them to
the student's skill set. # Expected output
3. Add skills with proficiency levels: Takes a dictionary of skills and
proficiency levels and adds to the skill set. {'Python': 'Beginner’,
'Java': 'Beginner’,
▪ Requirements 'C++': 'Beginner’,
'Data Analysis': 'Advanced’,
• Use the multipledispatch library to achieve function overloading. 'Machine Learning': 'Intermediate'}
• Implement the Person and Student classes.
• Implement the add_skill method in the Student class using function
overloading. 52
Web Developer-Python
Question?

Web Developer-Python 53
5. Operator Overloading

Web Developer-Python 54
Operator overloading

What is operator overloading?

Operator overloading in Python allows to define how operators behave with user-defined objects.

For example, the ‘+’ operator will perform arithmetic addition on two numbers, merge two lists, or concatenate
two strings.

Web Developer-Python 55
Operator overloading

What is function overloading ?

It refers to the ability to define multiple functions with the same name but different type or number of parameters.

Web Developer-Python 56
Operator overloading

How does the operator overloading work?

Step1: Defining Special Methods

Step2: Invocation of Special Methods

Step3: Returning Results

Web Developer-Python 57
Operator overloading

What is special method?

▪ Python provides a set of special methods for operator overloading.

▪ Also known as magic methods or dunder methods (because their names are surrounded by double underscores).

▪ These methods allow to define how instances of class behave with operators.

Web Developer-Python 58
Operator overloading

Built-in special methods for overloading


Arithmetic Operators Unary Operators Type Conversion
▪ __add__(self, other) for + ▪ __neg__(self) for unary - ▪ __int__(self) for int()
▪ __sub__(self, other) for - ▪ __pos__(self) for unary + ▪ __float__(self) for float()
▪ __mul__(self, other) for * ▪ __abs__(self) for abs() ▪ __complex__(self) for complex()
▪ __truediv__(self, other) for / ▪ __invert__(self) for ~ ▪ __bool__(self) for bool()
▪ __floordiv__(self, other) for // ▪ __str__(self) for str()
▪ __mod__(self, other) for % Comparison Operators ▪ __repr__(self) for repr()
▪ __pow__(self, other) for ** ▪ __eq__(self, other) for ==
▪ __divmod__(self, other) for divmod() ▪ __ne__(self, other) for != Augmented Assignment Operators
▪ __lt__(self, other) for < ▪ __iadd__(self, other) for +=
Container/Sequence Operations ▪ __le__(self, other) for <= ▪ __isub__(self, other) for -=
▪ __len__(self) for len() ▪ __gt__(self, other) for > ▪ __imul__(self, other) for *=
▪ __getitem__(self, key) for indexing [] ▪ __ge__(self, other) for >= ▪ __itruediv__(self, other) for /=
▪ __setitem__(self, key, value) for assignment []= ▪ __ifloordiv__(self, other) for //=
▪ __delitem__(self, key) for deletion del [] Bitwise Operators ▪ __imod__(self, other) for %=
▪ __contains__(self, item) for in ▪ __and__(self, other) for & ▪ __ipow__(self, other) for **=
▪ __or__(self, other) for |
Context Management ▪ __xor__(self, other) for ^
__enter__(self) for entry ▪ __lshift__(self, other) for << 59
Web Developer-Python
__exit__(self, exc_type, exc_val, exc_tb) for exit ▪ __rshift__(self, other) for >>
Operator overloading

Built-in special methods for overloading

Other Special Methods Augmented Bitwise Assignment Operators


▪ __call__(self, *args, **kwargs) for function call () ▪ __iand__(self, other) for &=
▪ __iter__(self) for iteration ▪ __ior__(self, other) for |=
▪ __next__(self) for the next item in iteration ▪ __ixor__(self, other) for ^=
▪ __reversed__(self) for reversed() ▪ __ilshift__(self, other) for <<=
▪ __round__(self, n) for round() ▪ __irshift__(self, other) for >>=

Web Developer-Python 60
Operator overloading

__str__()
This method in Python is a special method used to
define a string representation of an object. It returns
a string whenever the object is printed or converted
to a string using str() function.

Find the output of the program.


Web Developer-Python 61
Operator overloading

# Example Usage

To demonstrate operator overloading using one operator from each category, class Point:
create a custom Point class and overload the following operators: def __init__(self, x=0, y=0):
self.x = x
self.y = y
▪ Arithmetic Operator: + (addition)
▪ Augmented Assignment Operator: += (in-place addition) # Expected Output
▪ Unary Operator: - (negation)
Addition: Point(4, 6)
▪ Comparison Operator: == (equality) In-place Addition: Point(4, 6)
Negation: Point(-4, -6)
▪ Bitwise Operator: & (bitwise AND)
Equality: False
▪ Type Conversion: int() (conversion to integer) Bitwise AND: Point(0, 2)
Integer Conversion: 10
▪ Container/Sequence Operation: [] (indexing)
Indexing: 4 6
▪ Context Management: with statement (context management) Entering context
Within context: Point(7, 8)
Exiting context

Web Developer-Python 62
Question?

Web Developer-Python 63
Thank you

Web Developer-Python 64

You might also like