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

Chapter 3 Python Object Oriented Programming

Uploaded by

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

Chapter 3 Python Object Oriented Programming

Uploaded by

Harshal Kadam
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 80

Chapter 3:-Python Object

Oriented Programming
OOP Terminology Overview

1) Class
The class is one of the Basic concepts of OOPs which is a group of similar
entities. Collection of objects is called class.It is only a logical component
and not the physical entity. Lets understand this one of the OOPs
Concepts with example, if you had a class called “Expensive Cars” it could
have objects like Mercedes, BMW, Toyota, etc. Its properties(data) can be
price or speed of these cars. While the methods may be performed with
these cars are driving, reverse, braking etc.

2) Object
An object can be defined as an instance of a class, and there can be multiple
instances of a class in a program. An Object is one of the Java OOPs
concepts which contains both the data and the function, which operates
on the data. For example – chair, bike, marker, pen, table, car, etc.
OOP Terminology Overview

3) Inheritance
Inheritance is one of the Basic Concepts of OOPs in which one object
acquires the properties and behaviors of the parent object. It’s creating
a parent-child relationship between two classes. It offers robust and
natural mechanism for organizing and structure of any software.

4) Polymorphism
Polymorphism refers to one of the OOPs concepts in Java which is the
ability of a variable, object or function to take on multiple forms. For
example, in English, the verb run has a different meaning if you use it
with a laptop, a foot race, and business. Here, we understand the
meaning of run based on the other words used along with it. The same
also applied to Polymorphism.
OOP Terminology Overview

5) Abstraction
Abstraction is one of the OOP Concepts in Java which is an act of representing
essential features without including background details. It is a technique of
creating a new data type that is suited for a specific application. Lets
understand this one of the OOPs Concepts with example, while driving a car,
you do not have to be concerned with its internal working. Here you just
need to concern about parts like steering wheel, Gears, accelerator, etc.

6) Encapsulation
Encapsulation is one of the best Java OOPs concepts of wrapping the data and
code. In this OOPs concept, the variables of a class are always hidden from
other classes. It can only be accessed using the methods of their current
class. For example – in school, a student cannot exist without a class.
Python Classes and Objects

A class is a user-defined blueprint or prototype


from which objects are created. Classes provide
a means of bundling data and functionality
together. Creating a new class creates a new
type of object, allowing new instances of that
type to be made. Each class instance can have
attributes attached to it to maintain its state.
Class instances can also have methods (defined
by their class) for modifying their state.
Syntax: Class Definition
class ClassName:
# Statement

Syntax: Object Definition


obj = ClassName()
• Creating a Python Class
Here, the class keyword indicates that you are creating a class followed by
the name of the class
class car:
pass
Example:-
# Create Class in .py file
class student:
def display(self): #define method in class
print (“hello python”)

Here self is default variable that contains memory address of instance of


current class.
Object of Python Class

In Python programming an Object is an instance of a Class. A class is like a


blueprint while an instance is a copy of the class with actual values.
An object consists of:
• 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.

Syntax:-
Obj name=class name()
Example
>>>Class student:
def display(self): #define method in class
Print(“hello python”)
>>>s1=student() #creating object of class
>>>s1.display() #calling method of class us obj.

o/p-
hello python
Python Class Variables

1) In Python, a class variable is a variable that is


defined within a class and outside of any class
method.
2) It is a variable that is shared by all instances
of the class, meaning that if the variable's
value is changed, the change will be reflected
in all instances of the class.
3) Class variables help store data common to all
instances of a class.
Creating a Class Variable

Example:-
class Employee:
office_name = "XYZ Private Limited" # This is a
class variable
In this example, the office_name variable is a
class variable, and it is shared among all
instances of the Employee class.
Accessing a Class Variable in Python

1) In Python you can access class variables in


the constructor of a class.
2) The constructor is defined using the special
method __init__() and is called automatically
when an instance of a class is created.
Example

class Employee:
office_name = "XYZ Private Limited"
def __init__(self):
print(Employee.office_name)
my_instance = Employee()
o/p-
Modify value of Class Variable in Python

1) Like any other variables, class variables can


also be changed. In Python, you can modify a
class variable using the class name or an
instance of the class.
2) it is important to note that modifying a class
variable using an instance of the class only
modifies the variable for that instance, not for
all instances of the class or the class itself.
Example
class Employee:
# Class variable
office_name = 'XYZ Private Limited'

# Constructor
def __init__(self, employee_name, employee_ID):
self.employee_name = employee_name
self.employee_ID = employee_ID

def show(self):
print("Name:", self.employee_name)
print("ID:", self.employee_ID)
print("Office name:", Employee.office_name)

# create Object
e1= Employee('Ram', 'T0166')
print('Before')
e1.show()

# Modify class variable


Employee.office_name = 'PQR Private Limited'
print('After')
e1.show()
output
Python Instance variable
1) A class in which the value of the variable vary
from object to object is known as instance
variables. An instance variable, in object-
oriented programming, is a variable that is
associated with an instance or object of a
class.
2) Instance variables are unique for each
instance while class variables are shared by
all instances.
Creating an Instance Variable

class Employee:
def __init__(self, name, id):
self.name = name
self.id = id
self.salary = 0

In this example, we define an Employee class with three


instance variables, name, id, and salary. We set the first two
instance variables, name and id, in the __init__ method.
We also set the salary instance variable to a default value of
0.
Accessing an Instance Variable in Python

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

employee1 = Employee("John Doe", 123)


employee2 = Employee("Jane Smith", 456)

print(employee1.name)
print(employee1.id)

print(employee2.name)
print(employee2.id)

• In this example, we define an Employee class with two instance variables, name, and id. We then create
two class instances, employee1, and employee2, and set their name and id instance variables using
the init method.
• We can then access the instance variables of each employee instance using the dot notation, as
demonstrated in the print statements. For example, employee1.name returns the first employee's name,
"John Doe".
OUTPUT
Modify value of an Instance Variable

class Employee:
# constructor
def __init__(self, employee_name, employee_ID):
# Instance variable
self.employee_name = employee_name
self.employee_ID = employee_ID

# create object
e1 = Employee("Ram", "T0166")

print("Before")
print("Employee name:", e1.employee_name, "Employee_ID:", e1.employee_ID)

# modify instance variable


e1.employee_name = "John"
e1.employee_ID = "T0167"
Output
Delete instance variable in python

class Employee:
def __init__(self, employee_name, employee_ID):
# Instance variable
self.employee_name = employee_name
self.employee_ID = employee_ID

# create object
e1 = Employee('Ram', 'T0166')

print(e1.employee_name, e1.employee_ID)
# del name
del e1.employee_name
print(e1.employee_name)
OUTPUT
Methods in a Python Class

A method in a class is a function that is


associated with an object. It defines the
behavior and actions that objects of the class
can perform. Methods are essential for
encapsulating functionality and promoting
code reusability. They are defined inside a
class and can access the attributes (variables)
of the class.
Syntax of Method
class ClassName:
def method_name(self, parameter1, parameter2, …):
# Method body – code goes here
# Creating an object of the class
object_name = ClassName()
# Calling a method on the object
object_name.method_name(argument1, argument2,
…)
Define and Call Methods In A Class In Python

1) Simple Class with a Method


class GeeksClass:
def say_hello(self):
print("Hello, Geeks!")

# Creating an object of GeeksClass


geeks_object = GeeksClass()

# Calling the say_hello method


geeks_object.say_hello()

# in this example, we define a class GeeksClass with a method say_hello. The say_hello
method simply prints the message “Hello, Geeks!” when called. We then create an
instance of the class (geeks_object) and call the say_hello method on that instance.
2) Class with Parameterized Method
class Calculator:
def add(self, num1, num2):
return num1 + num2

# Creating an object of Calculator


calculator_object = Calculator()

# Calling the add method with parameters


result = calculator_object.add(5, 7)
print("Result of addition:", result)

# In this example, we define a Calculator class with an add method that takes two parameters
(num1 and num2) and returns their sum. We create an instance of the Calculator class
(calculator_object) and call the add method with arguments 5 and 7.
Constructors in Python

Constructors are generally used for instantiating an


object. The task of constructors is to
initialize(assign values) to the data members of the
class when an object of the class is created. In
Python the __init__() method is called the
constructor and is always called when an object is
created.
• Syntax of constructor declaration :
def __init__(self):
# body of the constructor
Example
Ex. Define class rectangle which can be constructed by length and
width.The rectangle class has method which compute the area.

class Rectangle():
def __init__(self, l, w):
self.length = l
self.width = w
Def area(self):
return self.length*self.width
r=Rectangle(2,10)
Print(r.area())
Types of constructors :
1) default constructor: The default constructor is a simple
constructor which doesn’t accept any arguments. Its
definition has only one argument which is a reference to the
instance being constructed.

2) parameterized constructor: constructor with parameters is


known as parameterized constructor. The parameterized
constructor takes its first argument as a reference to the
instance being constructed known as self and the rest of the
arguments are provided by the programmer.
Example of default constructor :
Class student:
def_init_(self):
print(“non parametrised constructor”)
def show(self,name):
print(“Hello”,name)
S1=student()
S1.show(“rahul”)

o/p-
non parametrised constructor
Hello rahul
Example of the parameterized
constructor :
Class student:
def_init_(self,name):
print(“ parametrised constructor”)
Self.name=name
def show(self):
print(“Hello”,self.name)
S1=student(“rahul”)
S1.show

o/p-
parametrised constructor
Hello rahul
Examples
Q.1)Write python program to create class phone and access global variable

# Global variable
brand_name = "Motorola"

class Phone:
# Constructor to initialize instance variables
def __init__(self, model, price):
self.model = model
self.price = price

# Method to display phone details


def display_details(self):

# Access the global variable 'brand_name'


print(f"Brand: {brand_name}")
print(f"Model: {self.model}")
print(f"Price: ${self.price}")

# Main code
if __name__ == "__main__":

# Creating an instance of the Phone class


my_phone = Phone("X123", 699)
# Display details of the phone
my_phone.display_details()

o/p-
Brand: Motorola
Q.2)Write python program to create class student and one method and display student name and reg.no

class Student:

# Constructor to initialize instance variables


def __init__(self, name, reg_no):
self.name = name # Student's name
self.reg_no = reg_no # Student's registration number

# Method to display student details


def display_details(self):
print(f"Student Name: {self.name}")
print(f"Registration Number: {self.reg_no}")

# Main code
if __name__ == "__main__":

# Create an instance of the Student class


student1 = Student("Alice Johnson", "REG20241001")
# Display the details of the student
student1.display_details()

o/p-

Student Name: Alice Johnson


Registration Number: REG20241001
Destructors in Python

1) Destructors are called when an object gets


destroyed.
2) The __del__() method is a known as a
destructor method in Python. It is called when
all references to the object have been deleted
i.e when an object is garbage collected.
• Syntax of destructor declaration :
def __del__(self):
# body of destructor
EXAMPLE
# Python program to illustrate destructor
class Employee:

# Initializing
def __init__(self):
print('Employee created.')

# Deleting (Calling destructor)


def __del__(self):
print('Destructor called, Employee deleted.')

obj = Employee()
del obj

o/p-
Employee created
Destructor called, Employee deleted
Built-In Class Attributes in Python

1) _dict__
Dictionary containing the class namespace

2)__doc__
If there is a class documentation class, this returns it. Otherwise, None

3)__name__
Class name.

4) __module__
Module name in which the class is defined. This attribute is "__main__" in interactive mode.

5) __bases__
A possibly empty tuple containing the base classes, in the order of their occurrence in the
base class list.
Python Inheritance

1) Inheritance allows us to define a class that inherits all the methods and
properties from another class.

2) In inheritance, the child class acquires the properties and can access all the
data members and functions defined in the parent class. A child class can
also provide its specific implementation to the functions of the parent class.
In this section of the tutorial, we will discuss inheritance in detail.
3) In python, a derived class can inherit base class by just mentioning the base
in the bracket after the derived class name. Consider the following syntax to
inherit a base class into the derived class.
• Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of
them inside the bracket. Consider the following syntax.
• Syntax
class derive-
class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()

o/p-
dog barking
Animal Speaking
Python Multi-Level inheritance

1) Multi-Level inheritance is possible in python


like other object-oriented languages.
2) Multi-level inheritance is archived when a
derived class inherits another derived class.
There is no limit on the number of levels up to
which, the multi-level inheritance is archived
in python.
• Syntax

class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
.
.
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()

o/p-
dog barking
Animal Speaking
Eating bread...
Python Multiple inheritance

Python provides us the flexibility to inherit


multiple base classes in the child class.
• Syntax

class Base1:
<class-suite>

class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>

class Derived(Base1, Base2, ...... BaseN):


<class-suite>
Example

class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))

O/P-
30
200
0.5
Hierarchical Inheritance
If multiple derived classes are created from the
same base, this kind of Inheritance is known
as hierarchical inheritance.
In this instance, we have two base classes as a
parent (base) class as well as two children
(derived) classes.
• # Python program for demonstrating Hierarchical inheritance

# Here, we will create the Base class


class Parent1:
def func_1(self):
print ("This function is defined inside the parent class.")

# Derived class1
class Child_1(Parent1):
def func_2(self):
print ("This function is defined inside the child 1.")

# Derivied class2
class Child_2(Parent1):
def func_3(self):
• print ("This function is defined inside the child 2.")

# Driver's code
object1 = Child_1()
object2 = Child_2()
object1.func_1()
object1.func_2()
object2.func_1()
object2.func_3()

O/P-

This function is defined inside the parent class.


This function is defined inside the child 1.

This function is defined inside the parent class.


This function is defined inside the child 2.
Super class

In Python, the super() function is used to refer to the parent class or


super class.
It allows you to call methods defined in the super class from the
subclass, enabling you to extend and customize the functionality
inherited from the parent class.

Use of super()
In Python, super() has two major use cases:
• Allows us to avoid using the base class name explicitly
• Working with Multiple Inheritance
EXAMPLE
class Emp():
def __init__(self, id, name, Add):
self.id = id
self.name = name
self.Add = Add

# Class freelancer inherits EMP


class Freelance(Emp):
def __init__(self, id, name, Add, Emails):
super().__init__(id, name, Add)
self.Emails = Emails

Emp_1 = Freelance(103, "Suraj kr gupta", "Noida" , "KKK@gmails")


print('The ID is:', Emp_1.id)
print('The Name is:', Emp_1.name)
print('The Address is:', Emp_1.Add)
print('The Emails is:', Emp_1.Emails)

Output :
The ID is: 103
The Name is: Suraj kr gupta
The Address is: Noida
The Emails is: KKK@gmails

//In the given example, The Emp class has an __init__ method that initializes the id, and name and Adds attributes. The Freelance class inherits from
the Emp class and adds an additional attribute called Emails. It calls the parent class’s __init__ method super() to initialize the inherited attribute.
Method Overriding in Python

• The Python method overriding refers to defining a


method in a subclass with the same name as a
method in its superclass. In this case, the Python
interpreter determines which method to call at
runtime based on the actual object being referred to.
• You can always override your parent class methods.
One reason for overriding parent's methods is that
you may want special or different functionality in
your subclass.
# define parent class
class Parent:
def myMethod(self):
print ('Calling parent method')
# define child class
class Child(Parent):
def myMethod(self):
print ('Calling child method')
# instance of child
c = Child()
# child calls overridden method
c.myMethod()

output −
Calling child method
Operator Overloading

• As we know, the + operator can perform addition


on two numbers, merge two lists, or concatenate
two strings.
• we can use the + operator to work with user-
defined objects as well. This feature in Python,
which allows the same operator to have different
meanings depending on the context is
called operator overloading.
EXAMPLE
print (14 + 32)

# Now, we will concatenate the two strings


print ("Java" + "Tpoint")

# We will check the product of two numbers


print (23 * 14)

# Here, we will try to repeat the String


print ("X Y Z " * 3)

• Output:
46
JavaTpoint
322
XYZXYZXYZ
Python methods or special functions for operator overloading

Binary operators:-
Operaqtor Method
Operator Magic Method

+ __add__(self, other)

– __sub__(self, other)

* __mul__(self, other)

/ __truediv__(self, other)

// __floordiv__(self, other)

% __mod__(self, other)

** __pow__(self, other)

>> __rshift__(self, other)

<< __lshift__(self, other)

& __and__(self, other)

| __or__(self, other)

^ __xor__(self, other)
2) Comparison Operators:

Operator Magic Method

< __lt__(self, other)

> __gt__(self, other)

<= __le__(self, other)

>= __ge__(self, other)

== __eq__(self, other)

!= __ne__(self, other)
3) Assignment Operators:
Operator Magic Method

-= __isub__(self, other)

+= __iadd__(self, other)

*= __imul__(self, other)

/= __idiv__(self, other)

//= __ifloordiv__(self, other)

%= __imod__(self, other)

**= __ipow__(self, other)

>>= __irshift__(self, other)

<<= __ilshift__(self, other)

&= __iand__(self, other)

|= __ior__(self, other)

^= __ixor__(self, other)
Static & Class methods
Static Method:-
1) A static method is also a method that is
bound to the class and not the object of the
class.
2) This method can’t access or modify the class
state.
3)It is present in a class because it makes sense
for the method to be present in class.
Creating python static method

1) Using staticmethod():-

class Calculator:

def addNumbers(x, y):


return x + y

# create addNumbers static method


Calculator.addNumbers = staticmethod(Calculator.addNumbers)

print('Product:', Calculator.addNumbers(15, 110))

we called the addNumbers we created without an object. When we run this


program, here is the output we will get:
2)Using @staticmethod:-
class Calculator:
# create addNumbers static method @staticmethod
def addNumbers(x, y):
return x + y
print('Product:', Calculator.addNumbers(15, 110))
When we run this program, here is the output we will get:
classmethod():-
1) The classmethod() is an inbuilt function in Python, which returns a class
method for a given function
• Syntax:
classmethod( function )

We can also use the decorator form @classmethod for defining the classmethod.
• Syntax:
@classmethod < def function(cls, arg1, arg2, arg3...):
Where,
• function: this is the function that is required to be converted to a class
method
• returns: the converted class method of the function.
EXAMPLE
• # Python program to show how to create a simple classmethod function

# Defining a function
class Python:
course = 'Algorithm'

def algo(object_):
print("This is an algorithm: ", object_.course)

# Creating a classmethod function by passing a method to it


Python.algo = classmethod(Python.algo)
Python.algo()
• Output
This is an algorithm: Algorithm
Regular Expression

• A Regular Expression or RegEx is a special


sequence of characters that uses a search
pattern to find a string or set of strings.
• It can detect the presence or absence of a text
by matching it with a particular pattern and
also can split a pattern into one or more sub-
patterns.
Metacharacters in Python

Metacharacters are part of regular expression


and are the special characters that symbolize
regex patterns or formats.
Every character is either a metacharacter or a
regular character in a regular
expression.However, metacharacters have a
special meaning.
Metacharacter Description Example

[] It represents the set of "[a-z]"


characters.

It represents the special


\ "\r"
sequence.

It signals that any character


. is present at some specific "Ja.v."
place.

It represents the pattern


^ present at the beginning of "^Java"
the string.

It represents the pattern


$ present at the end of the "point"
string.

It represents zero or more


* occurrences of a pattern in "hello*"
the string.

It represents one or more


+ occurrences of a pattern in "hello+"
the string.

The specified number of


{} occurrences of a pattern the "java{2}"
string.

It represents either this or


| "java|point"
that character is present.

() Capture and group (javatpoint)


Python RegEx

• A RegEx, or Regular Expression, is a sequence of characters


that forms a search pattern.
• RegEx can be used to check if a string contains the specified
search pattern.

RegEx Module
Python has a built-in package called re, which can be used to
work with Regular Expressions.
Import the re module:
• import re
RegEx in Python

When you have imported the re module, you can start using regular expressions:

import re

#Check if the string starts with "The" and ends with "Spain":

txt = "The rain in Spain"


x = re.search("^The.*Spain$", txt)

if x:
print("YES! We have a match!")
else:
print("No match")

o/p-
YES! We have a match!
RegEx Functions

• The re module offers a set of functions that allows us


to search a string for a match:
Function Description
• Findall :-Returns a list containing all matches
• Search :-Returns a Match object if there is a match
anywhere in the string
• Split:- Returns a list where the string has been split at
each match
• Sub:- Replaces one or many matches with a string
The findall() Function
.

• The findall() function returns a list containing all matches

• Example

import re

#Return a list containing every occurrence of "ai":

txt = "The rain in Spain"


x = re.findall("ai", txt)
print(x)
o/p-
['ai', 'ai']
The search() Function

The search() function searches the string for a match, and returns a
Match object if there is a match.
• Example
Search for the first white-space character in the string:

import re
txt = "The rain in Spain“
x = re.search("\s", txt)
print("The first white-space character is located in position:", x.start())

o/p-
The first white-space character is located in position: 3
The split() Function

The split() function returns a list where the string has been split at each
match:

Example:-
import re

#Split the string at every white-space character:

txt = "The rain in Spain"


x = re.split("\s", txt)
print(x)
o/p-
['The', 'rain', 'in', 'Spain']
The sub() Function

The sub() function replaces the matches with the text of your
choice
• Example
Replace every white-space character with the number 9:

import re

txt = "The rain in Spain"


x = re.sub("\s", "9", txt)
print(x)
o/p-
The9rain9in9Spain
The search Function in Python

This function searches for first occurrence of


RE pattern within string with optional flags.
• Syntax
Here is the syntax for this function −
re.search(pattern, string, flags=0)
Parameter Description

Pattern This is the regular expression to


be matched.
string Searched to match pattern at
beginning of string

flags We specify different flags using


E-mail validation in python using regex

A regular expression is an important technique to


search the text and replace actions, validations,
string splitting, and many other operations
we can write a regular expression that can match
the most valid email addresses. First, we must
define the email address format we are looking
for.
Below is the most common email format is.
(user_name)@(domain_name).(top-leveldomain)
Validate Email Addresses with Python

Python provides the re-module that contains


classes and methods to represent and work
with Regular expressions in Python.
We will use this module in our Python script and
re.fullmatch(pattern, string, flags).
This method returns a match object only if the
whole string matches the pattern. If not
matched, return none
Example
import re

regex = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')

def emailValid(email):
if re.fullmatch(regex, email):
print("The given mail is valid")
else:
print("The given mail is invalid")
emailValid("sachin.sharma@gmail.com")
emailValid("johnsnow123@yahoo.co.uk")
emailValid("mathew123@...uk")
emailValid("...@domain.us")
• Output:
The given mail is valid
The given mail is valid
The given mail is invalid
The given mail is invalid

You might also like