Chapter 3 Python Object Oriented Programming
Chapter 3 Python Object Oriented Programming
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
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
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
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
# 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()
class Employee:
def __init__(self, name, id):
self.name = name
self.id = id
self.salary = 0
class Employee:
def __init__(self, name, id):
self.name = name
self.id = id
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)
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
# 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
# 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
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.
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
# Main code
if __name__ == "__main__":
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:
# Main code
if __name__ == "__main__":
o/p-
# Initializing
def __init__(self):
print('Employee created.')
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
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
class Base1:
<class-suite>
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
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
# 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-
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
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
output −
Calling child method
Operator Overloading
• 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)
| __or__(self, other)
^ __xor__(self, other)
2) Comparison Operators:
== __eq__(self, other)
!= __ne__(self, other)
3) Assignment Operators:
Operator Magic Method
-= __isub__(self, other)
+= __iadd__(self, other)
*= __imul__(self, other)
/= __idiv__(self, other)
%= __imod__(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:
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)
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":
if x:
print("YES! We have a match!")
else:
print("No match")
o/p-
YES! We have a match!
RegEx Functions
• Example
import re
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
The sub() function replaces the matches with the text of your
choice
• Example
Replace every white-space character with the number 9:
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