0% found this document useful (0 votes)
45 views62 pages

Chapter 0003

Uploaded by

bimalo2668
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views62 pages

Chapter 0003

Uploaded by

bimalo2668
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

• Introduction to OOP

• Classes and Objects

• Data member and member function

• self keyword

• Constructor and Destructor

• Inheritance and types

• super keyword

• Polymorphism

• Access specifiers
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Introduction to OOP

● Procedural programming is a method of writing software. It is a programming practice


centered on the procedures or actions that take place in a program.
● Object-oriented programming is centered on objects.
● Objects are created from abstract data types that encapsulate data and functions together.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Introduction to OOP

● An object is a software entity that contains both data and procedures. The data contained in
an object is known as the object’s data attributes. An object’s data attributes are simply
variables that reference data.
● The actions that an object performs are known as methods. An object’s methods are
functions that perform operations on the object’s data attributes.
● The object is, conceptually, a self-contained unit that consists of data attributes and methods
that operate on the data attributes.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Introduction to OOP (Encapsulation and Data Hiding )

● OOP addresses the problem of code and data separation through encapsulation and data hiding.
● Encapsulation refers to the combining of data and code into a single object.
● Data hiding refers to an object’s ability to hide its data attributes from code that is outside the object
● Only the object’s methods may directly access and make changes to the object’s data attributes.
● An object typically hides its data, but allows outside code to access its methods.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Introduction to OOP (Encapsulation and Data Hiding )

● When an object's internal data is hidden from outside code and access to that data is
restricted to the object’s methods, the data is protected from accidental corruption.
● In addition, the programming code outside the object does not need to know about the
format or internal structure of the object’s data.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Introduction to OOP (Object Reusability )

● In addition to solving the problems of code and data separation, the use of OOP has also
been encouraged by the trend of object reusability.
● An object is not a stand-alone program, but is used by programs that need its services.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Classes

● In Python, a class is a blueprint for creating objects, which are instances of the class.
● A class defines the properties and behaviors of objects of a particular type.
● Class contain properties (variables) and methods (functions) of object.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Definition of a class (Syntax)

class ClassName:

Data member # Variable

def member_function(self): # Function

Code….

# Declaring a variable of MyClass

my_object = ClassName()

my_object.member_function()

my_object.data_member
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example 1

class Jafri:

my_data_member = “Hello!”

def my_member_function(self):

print("This is my member function.")

# Declaring a variable of MyClass

my_object = Jafri()

my_object.my_member_function()

print(my_object.my_data_member)
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example 2

import random def toss(self):

# The Coin class simulates a coin that can be flipped. if random.randint(0, 1) == 0:


class Coin: self.sideup = 'Heads'
# The _ _init_ _ method initializes the sideup
else:
data attribute with 'Heads'.

def _ _init_ _(self): self.sideup = 'Tails'

self.sideup = 'Heads' def get_sideup(self):

return self.sideup
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example 2(Cont’)

# The main function. # Toss the coin.

def main(): print('I am tossing the coin ...')

# Create an object from the Coin class. my_coin.toss()

my_coin = Coin() # Display the side of the coin that is facing up.

# Display the side of the coin that is facing up. print('This side is up:', my_coin.get_sideup())
print('This side is up:', my_coin.get_sideup()) # Call the main function.

main()
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Object:

● Object is an instance of a class. It represents a real-world entity with some characteristics


(attributes) and behaviors (methods).

Syntax:

object_name1 = ClassName()

object_name2 = ClassName(param1, param2, ...)


Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example:

class MyClass:

my_data_member = None

def my_member_function(self):

print("This is my member function.")

my_object = MyClass()

# Access the data member and call the member function of my_object

my_object.my_data_member = "Hello, World!"

my_object.my_member_function()
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Data Member

● In object-oriented programming (OOP), a data member is a variable or field that is


associated with a class or an object.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example:

class Student:

# Data members

student_id = 0

student_name = "Jafri"

# Creating Object

student = Student()

print(student.student_id)

print(student.student_name)
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Member Function:

● A member function, also known as a method, is a function that is defined within a class and
operates on the data members and other members of that class.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example 1: # Creating an instance of the Student class

class Student: student = Student()

# Data members student.student_id = 100

student_id = 0 student.student_name = "JafriCode"

student_name = "" student.display_student_info()

# Member Function

def display_student_info(self):

print("Student ID:", self.student_id)

print("Student Name:", self.student_name)


Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example 2:
# The BankAccount class simulates a bank account. def withdraw(self, amount):

class BankAccount: if self._ _balance >= amount:

def _ _init_ _(self, bal): self._ _balance −= amount

self._ _balance = bal else:

def deposit(self, amount): print('Error: Insufficient funds')

self._ _balance += amount def get_balance(self):

return self._ _balance


Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example 2(Cont’):
import bankaccount # Display the balance.
print('Your account balance is $',
def main(): format(savings.get_balance(), ',.2f'), sep='')
# Get the starting balance.
start_bal = float(input('Enter your starting # Get the amount to withdraw.
balance: ')) cash = float(input('How much would you like to
savings = bankaccount.BankAccount(start_bal) withdraw? '))
print('I will withdraw that from your account.')
# Deposit the user's paycheck. savings.withdraw(cash)
pay = float(input('How much were you paid this
week? ')) # Display the balance.
print('I will deposit that into your account.') print('Your account balance is $',
savings.deposit(pay) format(savings.get_balance(), ',.2f'), sep='’)
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Accessor and Mutator Methods (Setters and Getters:

● As mentioned earlier, it is a common practice to make all of a class’s data attributes private,
and to provide public methods for accessing and changing those attributes. This ensures that
the object owning those attributes is in control of all the changes being made to them.
● A method that returns a value from a class’s attribute but does not change it is known as an
accessor method.
● Accessor methods provide a safe way for code outside the class to retrieve the values of
attributes, without exposing the attributes in a way that they could be changed by the code
outside the method.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Accessor and Mutator Methods (Setters and Getters:

● A method that stores a value in a data attribute or changes the value of a data attribute in some
other way is known as a mutator method.
● Mutator methods can control the way that a class’s data attributes are modified. When code
outside the class needs to change the value of an object’s data attribute, it typically calls a
mutator and passes the new value as an argument.
● If necessary, the mutator can validate the value before it assigns it to the data attribute.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Self Keyword:

● The "self" keyword typically refers to a reference to the current instance of a class or object.
● It is a convention used to refer to the instance of a class within its methods.
● When you define methods within a class, you include "self" as the first parameter in the method's definition
to represent the instance itself

Example:

class MyClass:

def Test(self, value):

self.value = value

def print_value(self):

print(self.value)
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

# Creating an instance of MyClass

obj = MyClass()

obj.Test(34)

# Accessing an instance variable and calling a method using "self"

obj.print_value()
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

List of common use cases for the "self" keyword:

Initializing Instance Variables: Calling Other Instance Methods:

def Test(self, name, age): def greet(self):

self.name = name self.print_info()

self.age = age

Accessing Instance Variables: Modifying Instance Variables:

def print_info(self): def update_age(self, new_age):

print(f"Name: {self.name}, Age: {self.age}") self.age = new_age


Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Constructor and Destructor:

● Constructor method (__init__()) is called automatically when an object is created.


● Destructor method (__del__()) is called automatically when an object is about to be
destroyed or garbage collected.
● Garbage collection is the process of automatically freeing up memory that is no longer
being used by the program

.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Types Constructor:

▪ Non- Parametrized Constructor

▪ Parametrized Constructor
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Non-Parametrized constructor example

class MyClass:

def __init__(self):

self.my_data_member = None

def my_member_function(self):

print("This is my member function.")

my_object = MyClass() # Creating an object of MyClass with a non-parameterized constructor

# Accessing the data member and calling the member function of my_object

my_object.my_data_member = "Hello, World!"

my_object.my_member_function()
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Parametrized constructor example

class Car: def get_descriptive_name(self):

def __init__(self, make, model, year): return f"{self.year} {self.make}

self.make = make {self.model}"

self.model = model my_car = Car("Audi", "A4", 2020)

self.year = year print(my_car.get_descriptive_name())

print("A new car has been created!") # Output: "2020 Audi A4"
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Destructor Example

class Car:

def __init__(self):

print("A new car has been created!")

def __del__(self):

print("The car is about to be destroyed!")

my_car = Car()
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Inheritance
● Inheritance is a key feature of object-oriented programming (OOP) that allows one class to inherit
attributes and methods from another class.
● Inheritance allows a new class to extend an existing class. The new class inherits the members of the class
it extends.
● In Python, inheritance is implemented using the class keyword, and the parent class is specified in
parentheses after the class name.
● When one object is a specialized version of another object, there is an “is a” relationship between them.
For example, a grasshopper is an insect.

Syntax:
class Subclass(Superclass):
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Inheritance

● Base Class (Parent Class): There is only one parent class from which the child class inherits. The
parent class defines a set of attributes and methods that can be reused by the child class.

● Child Class (Derived Class): The child class inherits all the attributes and methods from the parent
class. It can also add its own attributes and methods or override the inherited ones to customize the
behavior.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

# Parent class (or base class)

class ParentClass:

# Parent class attributes and methods

# Child class (or derived class) inheriting from ParentClass

class ChildClass(ParentClass):

# Child class attributes and methods


Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example 01:
class Vehicle: # Call methods on the child class object

def start(self): print(car.start())

return "The vehicle is starting." print(car.drive())

def stop(self): print(car.stop())

return "The vehicle is stopping."

class Car(Vehicle): # Child class

def drive(self):

return "The car is driving."

car = Car()
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example 02:

class A: obj_b = B()


def __init__(self):
print(obj_b.data_member_a)
self.data_member_a = "I am from class A"

def method_a(self): print(obj_b.method_a())

return "This is method A from class A" print(obj_b.method_b())


class B(A):

def method_b(self):

return "This is method B from class B"


Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Types of Inheritance:

▪ Single Inheritance

▪ Multiple Inheritance

▪ Multi-level Inheritance

▪ Hierarchical Inheritance
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Single Inheritance:

● It refers to a type of inheritance in which a class (the child or derived class) inherits
properties and behaviors (attributes and methods) from a single parent class (the base or
parent class).
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Single Inheritance:

class Parent: # Creating an object of the Child

def parent_method(self):
class

my_object = Child()
print("This is the parent
method.") # Calling methods from both the
Parent and Child classes
class Child(Parent):
my_object.parent_method()
def child_method(self):
my_object.child_method()
print("This is the child method.")
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Multiple Inheritance:
● A class inherits from more than one superclass. This is achieved by specifying multiple
superclass names in parentheses separated by commas when defining the subclass.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example:

class Parent1: class Child(Parent1, Parent2):

def child_method(self):
def parent1_method(self):
print("This is the child method.")
print("This is the parent1 method.")
# Creating an object of the Child class
class Parent2:
my_object = Child()
def parent2_method(self):
# Calling methods from all three classes
print("This is the parent2 method.")
my_object.parent1_method()

my_object.parent2_method()

my_object.child_method()
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Multi-level Inheritance:

● A class inherits from a superclass, which in turn inherits from another superclass.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example:

class Grandparent: class Child(Parent):

def grandparent_method(self): def child_method(self):

print("This is the grandparent method.") print("This is the child method.")

class Parent(Grandparent): # Creating an object of the Child class

def parent_method(self): my_object = Child()

print("This is the parent method.") my_object.grandparent_method()

my_object.parent_method()

my_object.child_method()
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

● Hierarchical Inheritance: A class has more than one subclass. This is achieved by defining
a superclass, and then defining multiple subclasses that inherit from the same superclass
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example:

class Parent: # Creating objects of the Child1 and Child2 classes


def parent_method(self): my_object1 = Child1()
print("This is the parent method.") my_object2 = Child2()
class Child1(Parent): # Calling methods from both Child classes
def child1_method(self): my_object1.parent_method()
print("This is the child1 method.") my_object1.child1_method()
class Child2(Parent): my_object2.parent_method()
def child2_method(self): my_object2.child2_method()
print("This is the child2 method.")
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Access specifiers:

● Access specifiers are a way of controlling the access to attributes and methods of a class in
object-oriented programming languages like C++ and Java.
● Access specifiers define the level of access that other classes or objects have to the attributes and
methods of a class.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Different Access specifiers in Python:

● Private: By convention, attributes and methods that are intended to be private are named with a double
leading underscore (__), It can be accessed within classonly. Private access modifier is the most secure
access modifier.
● Protected: Attributes and methods that are intended to be protected are named with a single leading
underscore (_).

It can be accessed within the class, outside the class and child class

● Public: Incase of public, no need to put underscore before data member or method name

It can be accessed within the class, outside the class and child class
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Public:

class MyClass: # Create an object of MyClass

def __init__(self): obj = MyClass()


self.public_var = 10 # Public attribute # Access the public variable and call the
public method
def public_method(self): print(obj.public_var) # Output: 10
return "This is a public method"
print(obj.public_method())
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example:

class Geek: # creating object of the class

# constructor obj = Geek("R2J", 20)

def __init__(self, name, age): # accessing public data member

# public data members print("Name: ", obj.geekName)

self.geekName = name # calling public member function of the class


obj.displayAge()
self.geekAge = age

# public member function Output

def displayAge(self): Name: R2J


Age: 20
# accessing public data member

print("Age: ", self.geekAge)


Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Protected:

class MyClass:

def __init__(self):

self._protected_var = 20 # Protected attribute

def _protected_method(self):

return "This is a protected method"


Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example: # accessing protected data members # creating objects of the


derived class
class Student: print("Roll: ", self._roll)

print("Branch: ", self._branch) obj = Geek("R2J", 1706256,


# protected data members
"Information Technology")
class Geek(Student):
_name = None
# calling public member
def __init__(self, name, roll, branch):
_roll = None functions of the class
Student.__init__(self, name, roll, branch)
_branch = None obj.displayDetails()
# public member function
def __init__(self, name, roll, branch):
def displayDetails(self):
self._name = name Output
# accessing protected data members of super
self._roll = roll class Name: R2J

self._branch = branch print("Name: ", self._name) Roll: 1706256


Branch: Information
# protected member function # accessing protected member functions of super class Technology
def _displayRollAndBranch(self): self._displayRollAndBranch()
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Private:

class MyClass:

def __init__(self):

self.__private_var = 30 # Private attribute

def __private_method(self):

return "This is a private method"


Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example:
# private member function # creating object
class Geek: def __displayDetails(self): obj = Geek("R2J", 1706256, "Information
Technology")
__name = None # accessing private data members

__roll = None print("Name: ", self.__name)


# calling public member function of the
print("Roll: ", self.__roll)
__branch = None class
print("Branch: ", self.__branch)
def __init__(self, name, roll, obj.accessPrivateFunction()
# public member function
branch):
def accessPrivateFunction(self):
self.__name = name Output
# accessing private member
Name: R2J
self.__roll = roll function
Roll: 1706256
self.__branch = branch self.__displayDetails()
Branch: Information Technology
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python


Example to illustrate the use of all the above three access modifiers (public, protected, and private) :

# super class # public member function


def displayPublicMembers(self):
class Super:
# accessing public data members
# public data member
print("Public Data Member: ", self.var1)
var1 = None # protected member function
# protected data member def _displayProtectedMembers(self):
_var2 = None # accessing protected data members

# private data member print("Protected Data Member: ", self._var2)


# private member function
__var3 = None
def __displayPrivateMembers(self):
# constructor
# accessing private data members
def __init__(self, var1, var2, var3):
print("Private Data Member: ", self.__var3)
self.var1 = var1
# public member function
self._var2 = var2 def accessPrivateMembers(self):
self.__var3 = var3 # accessing private member function
self.__displayPrivateMembers()
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

# derived class # calling public member functions of the class


class Sub(Super): obj.displayPublicMembers()
# constructor obj.accessProtectedMembers()

def __init__(self, var1, var2, var3): obj.accessPrivateMembers()


# Object can access protected member
Super.__init__(self, var1, var2, var3)
print("Object is accessing protected member:",
# public member function
obj._var2)
def accessProtectedMembers(self):
# object can not access private member, so it will
# accessing protected member functions of super
generate Attribute error
class
# print(obj.__var3)
self._displayProtectedMembers()
Output
# creating objects of the derived class
Public Data Member: Geeks
obj = Sub("Geeks", 4, "Geeks !") Protected Data Member: 4
Private Data Member: Geeks !
Object is accessing protected member: 4
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Polymorphism

● Polymorphism is a fundamental and a powerful concept in object-oriented programming.


● The term polymorphism refers to an object’s ability to take different forms.

Polymorphism different ways:

▪ Method overloading

▪ Method overriding
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Method Overloading:

● In Python, method overloading is not supported in the same way as in other languages like Java
and C++. However, we can achieve similar behavior using default argument values and variable
arguments.
● With method overloading, we can define multiple methods with the same name but with
different parameter lists. When we call a method, the appropriate version of the method is called
based on the number and types of arguments passed to it.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example:

class Math:

def add(self, x, y, z=0):

return x + y + z

m = Math()

print(m.add(1, 2)) # 3

print(m.add(1, 2, 3)) # 6
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Method Overriding:

● Method overriding is the process of defining a method in a subclass that has the same name
and parameters as a method in its superclass.
● When the method is called on an object of the subclass, the version of the method defined in
the subclass is executed, rather than the version in the superclass.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Example:

class Animal:

def speak(self):

print("Animal speaks.")

class Dog(Animal):

def speak(self):

print("Dog barks.")

a = Animal()

a.speak() # Animal speaks.

d = Dog()

d.speak() # Dog barks.


Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

super Keyword

● It is typically used within the child class to invoke a method that is overridden in the child class
but originally defined in the parent class.
● Using super keyword, we can access parent methods that are same with name.
● Its primary purpose is to provide a way to work with parent classes and their methods and
attributes in a child class.
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Usage of super() keyword in Python:

Calling the Parent Class Constructor:

class Parent:

def __init__(self):

print("Hi, i am Constructor of Parent")

class Child(Parent):

def __init__(self):

super().__init__()

# Call the constructor of the parent class

obj = Child()
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Calling the Parent Class Constructor (Initializer):

class Parent:

def __init__(self, name):

self.name = name

class Child(Parent):

def __init__(self, name, age):

super().__init__(name)

# Call the constructor of the parent class

self.age = age
Advanced Python

Chapter 03: Object-Oriented Programming (OOP) in Python

Calling Overridden Methods:

class Parent:

def greet(self):

print("Hello from Parent!")

class Child(Parent):

def greet(self):

super().greet() # Call the overridden method in the parent class

print("Hello from Child!")

obj = Child()

obj.greet()

You might also like