INTRODUCTION TO PYTHON PROGRAMMING Unit III
UNIT – V
OBJECT ORIENTED PROGRAMMING
In Python, object-oriented Programming (OOPs) is a programming paradigm that uses
objects and classes in programming. It aims to implement real-world entities like
inheritance, polymorphisms, encapsulation, etc. in the programming. The main concept of
OOPs is to bind the data and the functions that work on that together as a single unit so that
no other part of the code can access this data.
CLASSES AND OBJECTS
A class is a collection of objects. A class contains the blueprints or the prototype from
which the objects are being created. It is a logical entity that contains some attributes
and methods.
An object is any entity that has attributes and behaviors. For example, a parrot is an
object. It has
attributes - name, age, color, etc.
behavior - dancing, singing, etc.
CREATING CLASSES AND OBJECTS
To create a class, use the keyword class:
class ClassName:
# Statement-1
.
.
.
# Statement-N
Creating Class
class MyClass:
x = 5
OUTPUT:
<class '__main__.MyClass'>
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 1
INTRODUCTION TO PYTHON PROGRAMMING Unit III
Creating Object
p1 = MyClass()
print(p1.x)
OUTPUT
5
CONSTRUCTOR METHOD
Python uses a special method called a constructor method. Python allows you to define
only one constructor per class. Also known as the _init_() method, it will be the first
method definition of a class and its syntax is,
The _init_() method defines and initializes the instance variables. It is invoked as soon
as an object of a class is instantiated. The _init_() method for a newly created object is
automatically executed with all of its parameters. The _init_() method is indeed a
special method as other methods do not receive this treatment. The parameters for
_init_() method are initialized with the arguments that you had passed during
instantiation of the class object. Class methods that begin with a double underscore (__)
are called special methods as they have special meaning. The number of arguments
during the instantiation of the class object should be equivalent to the number of
parameters in _init_() method (excluding the self parameter).
SYNTAX
class MyClass:
def __init__(self, arg1, arg2, ...):
# Initialize attributes here
self.attribute1 = arg1
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 2
INTRODUCTION TO PYTHON PROGRAMMING Unit III
self.attribute2 = arg2
# ...
# Creating an object of MyClass and invoking the constructor
obj = MyClass(arg1_value, arg2_value, ...)
EXAMPLE:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Creating a Person object
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# Accessing the attributes of the objects
print(person1.name) # Output: Alice
print(person1.age) # Output: 30
print(person2.name) # Output: Bob
print(person2.age) # Output: 25
The self
Class methods have only one specific difference from ordinary functions - they must have an extra first
name that has to be added to the beginning of the parameter list, but you do do not give a value for this
parameter when you call the method, Python will provide it. This particular variable refers to the object
itself, and by convention, it is given the name self.
Although, you can give any name for this parameter, it is strongly recommended that you use the
name self - any other name is definitely frowned upon. There are many advantages to using a standard
name - any reader of your program will immediately recognize it and even specialized IDEs (Integrated
Development Environments) can help you if you use self.
Note for C++/Java/C# Programmers
The self in Python is equivalent to the self pointer in C++ and the this reference in Java and C#.
You must be wondering how Python gives the value for self and why you don't need to give a value for it.
An example will make this clear. Say you have a class called MyClass and an instance of this class
called MyObject. When you call a method of this object as MyObject.method(arg1, arg2), this is
automatically converted by Python into MyClass.method(MyObject, arg1, arg2 - this is what the
special self is all about.
This also means that if you have a method which takes no arguments, then you still have to define the
method to have a self argument.
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 3
INTRODUCTION TO PYTHON PROGRAMMING Unit III
CLASSES WITH MULTIPLE OBJECTS
A single class definition can be used to create multiple objects. As mentioned before,
objects are independent. Changes made to one object generally do not affect the other
objects representing the same class. Each object has its own unique set of data
attributes.
# define a class
class Employee:
# define an attribute
employee_id = 0
# create two objects of the Employee class
employee1 = Employee()
employee2 = Employee()
# access attributes using employee1
employee1.employeeID = 1001
print(f"Employee ID: {employee1.employeeID}")
# access attributes using employee2
employee2.employeeID = 1002
print(f"Employee ID: {employee2.employeeID}")
OUTPUT:
Employee ID: 1001
Employee ID: 1002
OBJECTS AS ARGUMENTS
In Python, you can pass objects as arguments to functions just like you would pass any
other data type, such as integers, strings, or lists. Objects can be instances of classes
you've defined or built-in classes like lists, dictionaries, etc.
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 4
INTRODUCTION TO PYTHON PROGRAMMING Unit III
When you pass an object as an argument to a function, you're essentially passing a
reference to that object. This means that any changes made to the object within the
function will affect the original object outside the function, as they both point to the
same memory location.
EXAMPLE:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def print_person_info(person):
print(f"Name: {person.name}, Age: {person.age}")
person_obj = Person("John Doe", 30)
print_person_info(person_obj) # Output: Name: John Doe, Age: 30
OBJECTS AS RETURN VALUES
A return statement is used to end the execution of the function call and “returns” the
result (value of the expression following the return keyword) to the caller. The
statements after the return statements are not executed. If the return statement is
without any expression, then the special value None is
returned. A return statement is overall used to invoke a function so that the passed
statements can be executed .
SYNTAX:
def fun():
statements
.
.
return [expression]
EXAMPLE
def create_person(name, age):
# Create an instance of the Person class
person = Person(name, age)
# Optionally, you can perform other operations on the person object
# before returning it.
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 5
INTRODUCTION TO PYTHON PROGRAMMING Unit III
return person
# Call the function to create a Person object and store it in the 'person_obj' variable
person_obj = create_person("Alice", 30)
# Access the attributes of the returned Person object
print(person_obj.name) # Output: Alice
print(person_obj.age) # Output: 30
INHERITANCE
Inheritance allows us to create a new class from an existing class.
The new class that is created is known as subclass (child or derived class) and the
existing class from which the child class is derived is known as superclass (parent or
base class).
The main purpose of inheritance is the reusability of code because we can use the
existing class to create a new class instead of creating it from scratch.
SINGLE AND MULTIPLE INHERITANCE
Single Inheritance
In single inheritance, a child class inherits from a single-parent class. Here is one child
class and one parent class.
class parent: # parent class
def func1(self):
print("Hello Parent")
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 6
INTRODUCTION TO PYTHON PROGRAMMING Unit III
class child(parent):
# child class
def func2(self): # we include the parent class
print("Hello Child") # as an argument in the child class
# Driver Code
test = child() # object created
test.func1() # parent method called via child object
test.func2() # child method called
Mulitple Inheritance
In multiple inheritance, a single child class is inherited from two or more parent classes.
It means the child class has access to all the parent classes' methods and attributes.
class parent1: # first parent class
def func1(self):
print("Hello Parent1")
class parent2: # second parent class
def func2(self):
print("Hello Parent2")
class parent3: # third parent class
def func2(self): # the function name is same as parent2
print("Hello Parent3")
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 7
INTRODUCTION TO PYTHON PROGRAMMING Unit III
class child(parent1, parent2, parent3): # child class
def func3(self): # we include the parent classes
print("Hello Child") # as an argument comma separated
# Driver Code
test = child() # object created
test.func1() # parent1 method called via child
test.func2() # parent2 method called via child instead of parent3
test.func3() # child method called
MULTILEVEL AND MULTIPATH INHERITANCE
Multilevel Inheritance
In multilevel inheritance, we go beyond just a parent-child relation. We introduce
grandchildren, great-grandchildren, grandparents, etc. We have seen only two levels of
inheritance with a superior parent classes and a derived classes, but here we can have
multiple levels where the parent classes itself is derived from another classes.
class grandparent: # first level
def func1(self):
print("Hello Grandparent")
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 8
INTRODUCTION TO PYTHON PROGRAMMING Unit III
class parent(grandparent): # second level
def func2(self):
print("Hello Parent")
class child(parent): # third level
def func3(self):
print("Hello Child")
# Driver Code
test = child() # object created
test.func1() # 3rd level calls 1st level
test.func2() # 3rd level calls 2nd level
test.func3() # 3rd level calls 3rd level
Multipath Inheritance
Multipath inheritance, also known as diamond inheritance or the diamond problem, is a
situation that can occur in object-oriented programming languages like Python when a
class inherits from two or more classes that have a common base class.
class A:
def show(self):
print("A")
class B(A):
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 9
INTRODUCTION TO PYTHON PROGRAMMING Unit III
def show(self):
print("B")
class C(A):
def show(self):
print("C")
class D(B, C):
pass
obj = D()
obj.show()
ENCAPSULATION- DEFINITION
Encapsulation is one of the fundamental concepts in object-oriented programming
(OOP). It describes the idea of wrapping data and the methods that work on data
within one unit. This puts restrictions on accessing variables and methods directly
and can prevent the accidental modification of data. To prevent accidental change, an
object’s variable can only be changed by an object’s method. Those types of variables
are known as private variables.
PRIVATE INSTANCE VARIABLES
In Python, instance variables are typically defined within a class and are used to store
data specific to each instance of the class. Private instance variables are variables that
are intended to be used only within the class and are not meant to be accessed directly
from outside the class. They are often prefixed with a double underscore (__) to indicate
their private nature.
Here's an example of how private instance variables can be used in a Python class:
class MyClass:
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 10
INTRODUCTION TO PYTHON PROGRAMMING Unit III
def __init__(self, value):
self.__private_var = value
def get_private_var(self):
return self.__private_var
def set_private_var(self, new_value):
self.__private_var = new_value
# Creating instances of the class
obj1 = MyClass(10)
obj2 = MyClass(20)
# Accessing private instance variables through methods
print(obj1.get_private_var()) # Output: 10
print(obj2.get_private_var()) # Output: 20
# Trying to access the private variable directly will result in an AttributeError
# print(obj1.__private_var) # This line would raise an AttributeError
# Modifying private instance variables through methods
obj1.set_private_var(15)
print(obj1.get_private_var()) # Output: 15
POLYMORPHISM- DEFINITION
The word polymorphism means having many forms. In programming, polymorphism
means the same function name (but different signatures) being used for different types. The
key difference is the data types and number of arguments used in function.
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 11
INTRODUCTION TO PYTHON PROGRAMMING Unit III
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def make_animal_speak(animal):
return animal.speak()
# Usage
dog = Dog()
cat = Cat()
print(make_animal_speak(dog)) # Output: "Woof!"
print(make_animal_speak(cat)) # Output: "Meow!"
OPERATOR OVERLOADING
Python that allows the same operator to have different meaning according to the
context is called operator overloading.
For example, the + operator will perform arithmetic addition on two numbers, merge
two lists, or concatenate two strings.
# Add 2 integer values
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 12
INTRODUCTION TO PYTHON PROGRAMMING Unit III
a = 1 + 6
print(a)
# Concatenate 2 strings
a = 'Python' + 'Program'
print(a)
# Concatenate 2 lists
a = ['A', 'B'] + [1, 2, 3]
print(a)
OUTPUT:
7
PythonProgram
['A', 'B', 1, 2, 3]
ASST PROF VEENA MORE A.S.P COLLEGE OF COMMERCE(AUTONOMOUS),VIJAYAPUR Page 13