0% found this document useful (0 votes)
2 views24 pages

Unit 5

Unit V of the Programming and Problem Solving notes covers Object Oriented Programming (OOP) concepts including classes, objects, methods, inheritance, polymorphism, containership, reusability, delegation, data abstraction, and encapsulation. It explains the significance of class and object definitions, the role of the self-argument in methods, and the use of the __init__() method as a constructor. The notes also differentiate between class variables and object variables, emphasizing their respective behaviors and accessibilities in OOP.

Uploaded by

chinmainair41
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)
2 views24 pages

Unit 5

Unit V of the Programming and Problem Solving notes covers Object Oriented Programming (OOP) concepts including classes, objects, methods, inheritance, polymorphism, containership, reusability, delegation, data abstraction, and encapsulation. It explains the significance of class and object definitions, the role of the self-argument in methods, and the use of the __init__() method as a constructor. The notes also differentiate between class variables and object variables, emphasizing their respective behaviors and accessibilities in OOP.

Uploaded by

chinmainair41
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/ 24

Department of First Year Engineering

Programming and Problem Solving


Unit- V Notes

Unit V: Object Oriented Programming


Structured and object oriented: Features of Object oriented programming-classes, objects,
methods
and message passing, inheritance, polymorphism, containership, reusability, delegation, data
abstraction and encapsulation.
Classes and Objects: classes and objects, class method and self-argument, __init__() method, class
variables and object variables, __del__() method, public and private members, Built in function to
check, Get, Set and Delete class attribute, Garbage collection, class methods, Static Method.

5.1 Structured and object oriented

5.1.1 Features of Object oriented programming


Q1. Explain features of OOP.
Or
Q1. Write a note on: 1. 2. 3.

1. Classes
A class is user-defined data type used to describe something in the world, such as occurrences, things,
external entities, and so on.
A class describes template or blueprint that describes the structure and behavior of a set of similar
objects.
Once we have definition for a class, a specific instance of that class can be easily created.
For eg. Consider a class student. A student has attributes such a roll_no, name, course and aggregate.
The operations that can be performed on its data may include ‘getdata’, ‘setdata’,’editdata’ and
so on.
A class is collection of objects.

1 Unit III: Functions and Strings FE PPS 2024


2. Objects
Object is basic unit of object-oriented programming. Object is basic run-time entity in an object-
oriented system.
Anything having its own properties can be considered as an object.
For example flower is an object having properties such as name, fragrance, etc. An object is a collection
of data members and associated member function also known as methods shown in figure1 below:

Object Name
Attribute 1
Attribute 2

.........
Attribute N
Function 1
Function 2

.........
Function N
Fig1. Representation of an Object

3. Methods and Message passing Methods


A method is a function associated with class.
It defines the operations that the object can execute when it receive a message. In object oriented
language, only methods of the class can access and manipulate the data stored in an instance of
the class (or object).
Figure2 shows how a class is declared using its data members and member functions.

2 Unit III: Functions and Strings FE PPS 2024


Figure2. Objects sending a message

Message Passing
Two objects communicate with each other though messages.
An object asks another object to involve one of its methods by sending it a message.
In figure2 sender object is sending message to the receiver object to get details of a student. i.e. the
sender is passing some specific information to the receiver so that the receiver can send the correct
and precise information to the sender. The data that is transferred with the message is called
parameters. Here, roll_no 1 is the parameter.
The messages that are sent to other objects consist of three aspects-the receiver object, the name of
the method that the receiver should invoke, and the parameters that must be used with the method.

4. Inheritance (‘is-a’ relation)


Inheritance is a concept of OOP in which a new class is created from an existing class.
The new class, often known as a subclass, contains the attributes and methods of the parent class. (the
exiting class from which the new class is created).
The new class, known as a subclass or derived class, inherits the attributes and behaviour of pre-
existing class, which is referred to as superclass or parent class. (refer figure3.)

Figure3: Child, derived or subclass

3 Unit III: Functions and Strings FE PPS 2024


The inheritance relationship of a subclasses and superclasses generates a hierarchy. Therefore
inheritance relation is also called as ‘is-a’ relation. A subclass not only has all the states and behavior
associated with superclass but has other specialized features (additional data or methods) as well. The
main advantage is ability to reuse the code. For example, we have a class student with following
members: Properties: rollno, name, course, marks Methods: getdata, setdata.

Student

Undergraduate Postgraduate
Student Student

Figure4. Example of Inheritance

We can inherit two classes from the class student- undergraduate students and postgraduate students
(refer figure4). These two classes will have all the properties of class students and in addition
to that it will have even more specialized members.
When a derived class receives a message to execute a method, it finds the method in its own
class. If it finds the method, then it simply executes it. If the method is not present, it searches for that
method in its superclass. If the method is found, it is executed; otherwise, an error message is reported.

5. Polymorphism
 Polymorphism refers to having several different forms.
 While inheritance is related to classes and their hierarchy, polymorphism on other hand,
is related to methods.
 Polymorphism is a concept that enables the programmers to assign a different meaning or
usage to a method in different context.
 Polymorphism exist when a number of subclasses is defined which have methods of
same name.
 Polymorphism can also be applied to operators.

4 Unit III: Functions and Strings FE PPS 2024


6. Containership (composition or has-a’ relationship )
 Containership is ability of a class to contain object(s) of one or more classes a member data.
 For example, class Person can have an object of class Student as its data member. This would
allow the object of class Person to call the public functions of class Student. Here class Person
becomes the container, whereas class Student becomes the contained class.
 Containership is also called composition because as in given example, class Person is
composed of class Student.
 In OOP, containership represents a ‘has-a’ relationship.

7. Reusability
 Reusability means developing codes that can be reused either in the same program or in
the different programs.
 Reusability is attained through inheritance, containership and polymorphism.

8. Delegation
 To provide maximum flexibility to programmers and to allow them to generate a reusable code,
object oriented languages also support delegation.
 In composition, an object can be composed of other objects and thus, the object exhibits a ‘has-
a’ relationship.
 In delegation, more than one object is involved in handling a request. The object that receives
the request for a service, delegates it to another object called its delegate.
 Delegation means that one object is dependent on another object to provide functionalities.
 The property of delegation emphasizes on the ideology than a complex object is made of several
simpler objects.
 For example, our body is made up of brain, heart, hands, eyes, ears, etc. The functioning
of the whole body as a system rests on the correct functioning of the parts it is composed of.
 Delegation is different from inheritance in the way that two classes that participates
in inheritance share ‘is-a’ relationship; however, in delegation, they have a ‘has-a’ relationship.

9. Data Abstraction
 Data Abstraction refers to the process by which data and functions are defined in such a way
5 Unit III: Functions and Strings FE PPS 2024
that only essential details are revealed and the implementation details are hidden.
 The main focus of data abstraction is to separate the interface and implementation of
a program.
 For example, as user of television sets, we can switch it on or off, change the channel, set
the volume and add external devices such as speakers and CD or DVD players without
knowing the details how its functionality has been implemented.
 Therefore, the implementation is completely hidden from external world.

10. Encapsulation (Data hiding)


 Data encapsulation, also called data hiding, is the technique of packing data and functions into
a single component (class) to hide implementation details of a class from users.
 Users are allowed to execute only a restricted set of operations (class methods) on the data
members of the class.
 Therefore encapsulation organizes the data and methods into a structure that prevents data
access by any function (or method) that is not specified in the class. This ensures the
integrity of the data contained in the object.
 Encapsulation defines three access levels for data variables and member functions of
the class. These access levels specify the access rights, explained as follows:
1) Any data of function with access level as p ublic can be accessed by any function belonging
to any class. This is lowest level of data protection.
2) Any data of function with access level as protected can be accessed only by that class or
by any class that is inherited from it.
3) Any data of function with access level as private can be accessed only by the class in
which it is declared. This is highest level of data protection.

5.2 Classes and Object


Q4. Explain class and object with suitable examples. Ans.
A class creates new data type and object is an instance (or variable) of the class. Classes provide a
blueprint or a template using which objects are created.
In fact, in Python, everything is an object o an instance of some class.
For example, all integer variables that we define in our program are actually instances of class
int. We can find out the type of any object using the type() function.
6 Unit III: Functions and Strings FE PPS 2024
Defining Classes
Python has very simple syntax of defining a class. Syntax is given below:

class class_name:
<statement-1>
<statement-2>

.
.
.
<statement-N>

It starts with a keyword class followed by the class_name and colon (:)
The statement in the definition can be any of these —
o Sequential instructions,
o Decision control statements
o Loop statements and
o Function definition
Variables defined in the class are called class variables and functions defined inside a class are
called class method. Class variables and class methods are together known as class members.
The class members can be accessed through class objects.
Class definitions can appear anywhere in a program, but they usually written near the beginning
of the program, after import statement.
When a class definition is entered, a new namespace is created, and used as the local scope.

Creating Objects
Once a class is defined, the next job is to create an object (or instance) of that
class. The object can then access class variables and class methods using dot operator (.)
The syntax to create an object is given as:

Object_name=class_name()

Creating an object or instance of a class is known as class instantiation. Class instantiation uses
function notation.
7 Unit III: Functions and Strings FE PPS 2024
The syntax for accessing a class member through the class object is:

Object_name.class_member_name

Program to access class variable using class object

class ABC:
var=10
obj=ABC() #Object obj is created of class ABC
print(obj.var)
OUTPUT
10

In the above program, we have defined a class ABC which has var having a value of 10. The
object of the class is created and used to access the class variable using dot operator.

5.3 Class Method and Self-argument

Q6. What does the self argument signify in the class methods?
Ans.
Class Method definition is nothing but Function Definitions, exactly same as ordinary
functions.
Syntax:

Class Class_name:
def function_name(self):
Statement 1
Statement 2
.
.
Statement n

8 Unit III: Functions and Strings FE PPS 2024


Class method must have the first argument named as self. Moreover we do not pass any value for this
parameter.
When we call the method, python provide its value automatically. Self-argument refers to the
object itself.
This means that even that method that takes no arguments, it should be defined to accept the self.
self is just a parameter in function and user can use any parameter name in place of it. But it is advisable
to use self because it increase the readability of code.
Example:

Output:
Roll no of Student is 10

5.4 The init () Method (The class constructor)

Q7. Explain the significance of init ( ) method.


Ans.
Python supports a very unique method named as init () method. This method gets executed
when instance of a class gets created (i.e.- when objects get created).
It is also called as an initializer method or constructor in object oriented programming.
It is useful to initialize the variables of the class objects.
First parameter of this method is called as self, means instance/object of the class. This method is
prefixed as well as suffixed with double underscore symbol

9 Unit III: Functions and Strings FE PPS 2024


Syntax:
Class Class_name:
def init (self [,argument list]):
Statement 1
Statement 2
.
.
Statement n

class student: #class Defination


def init (self, marks): # Class Method (Constructor)
self.marks=marks
print ("Marks of a Student is",self.marks)

obj1=student(70) #Object 1 Created


obj2=student(80) #Object 2 Created

5.5 Class variables and Object variables

Q8. Write a note on class variables and object variables with example. Ans.
Class Variable:
Class variables are used to declare within a class. These variables have same value across all instances
(objects). These variables are also called as static variables. All the objects/Instance of the class will
share the class variable. Since there exist only one copy of the class variable, any changes made to the
class variable by an object will be reflected in all other objects/instances.
Syntax to access class variable:

className. Class_variable
here className is the name of the class and class_variable is the class variable defined in the
class.

10 Unit III: Functions and Strings FE PPS 2024


Example1:
Class student: # Class definition
rollno =10 # Class Variable

print("class variable value is ", student.rollno) #printed class variable

Class variables are created and assigned values within declaration itself. You can also access class
variables with an object created within a class
Example 2:
Class student: # Class definition
rollno =10 # Clas Variable
def display(self):
print("class variable value is ", self.rollno) #printed class
variable

obj= student()

Object Variable:
Object variable or instance variable have different value for each new instance. If a class has N
instances/Objects, then there will be a N separate copies of the object variable as each
object/instances have its own object variable. Object variables are not shared between other objects.
A change made to the object variable by one object, will not be replicated in other objects.

11 Unit III: Functions and Strings FE PPS 2024


Example1:
class student: #class Defination
serial_No=0 # Class Variable
def init (self, marks): # Class Method (Constructor)
student.serial_No+=1
self.marks=marks
print(("Serial number is" , self.serial_No)
print ("Marks of a Student is",self.marks)

obj1=student(70) #Object 1 Created


obj2=student(80) #Object 2 Created

Example 2:

class student: #class Defination


serial_No=0 # Class Variable
def display(self, marks): # Class Method
student.serial_No+=1
self.marks=marks
print(("Serial number is", self.serial_No)
print ("Marks of a Student is",self.marks)

obj1=student() #Object 1 Created


obj2=student() #Object 2 Created
obj1.display(70) #Method call
obj2.dispaly(80) #Method call

12 Unit III: Functions and Strings FE PPS 2024


Q9. Differentiate between class variables and instance variables.
Ans: We have seen that a Class can have variables defined in it. Basically these variables are of two
types:
a) Class Variables
b) Instance Variables
As the name suggests the class variables are owned by the class and Instance (Object)
variables are owned by each object.
Important points are as follows:
If a class has n objects, then there will be n separate copies of the object variable as each object will
have its own object variable.
The object variable is not shared between objects.
A change made to the object variable by one object will not be reflected in other objects.
If the class has one class variable, then there will be one copy only for that variable. All the objects of
that class will share the class variable.
Since there exists only one copy of class variable, any change made to the class variable will
be reflected in all other objects.
Program to differentiate between object and class variables

class Car:
wheels = 4 #Class Variable
def init (self, comp):
self.company = comp # Object/Instance Variable
print("The company(Object Var) : ", self.company)
print("The Wheels(Class var) : ", Car.wheels)
obj1 = Car("Mercedez")
obj2 = Car("BMW")
Output:
The company(Object Var) : Mercedez
The Wheels(Class var) : 4
The company(Object Var) : BMW
The Wheels(Class var) : 4

13 Unit III: Functions and Strings FE PPS 2024


In the above example, following points should be noted:
The class Variable wheels is having default value 4, which is same for all types of Cars. Such
variables are declared as class variable, which is common to all.
Whereas the Company of car is depends on the particular car and it may varies for different cars.
Such variables are declared as a Instance Variables.
The Object or Instance variables are declared/ initialized inside init () or member function of a
class
The class variable are declared / Initialized outside of any function in class.

5.6 The del () method

Q10. Explain del () method with example.


We saw init () method which initializes object.
Similar to init () method we have del () method which does just the opposite work.
The del () method is automatically called when the object goes out of scope.
This is the time when object will no longer used and its occupied resources are return back to
system
Returned resources can be used for some other work.
You can explicitly delete the object by del keyword, so that del () method will get called.

class ABC:
def init (self, var):
self.var = var
print("The object value is =", var)
def del (self):
print("Object with value %d is going out of scope"%self.var)

obj1 = ABC(10) # Creating obj1, init () get called


obj2 = ABC(20) #Creating obj2, init () get called

14 Unit III: Functions and Strings FE PPS 2024


del obj1 # Deleting obj1 explicitly, del () get called
del obj2 # Deleting obj2 explicitly, del () get called

Output:
The object value is = 10
The object value is = 20
Object with value 10 is going out of scope
Object with value 20 is going out of scope

In the above program init () method is automatically called when object is created.
del () method is also automatically called when object is deleted.
We are deleting object explicitly, by del objectName. So while object is getting deleted del
() method is called.

5.7 Public and Private Members

Q11. Explain public and private members with suitable example. Ans.
Ans:
Public variables are the variables which are declared inside class and can be accessed from anywhere
in the program using the dot (.) operator.
It means public variables can be accessed from within the class as well as from outside the
class in which it is defined.
Private Variables are defined in the class with double underscore prefix ( ). Private
variables are accessible from only within the class and from nowhere outside the class.

class ABC:
def init (self, val1, val2):
self.var1 = val1 # var1 is public variable
self. var2= val2 # var2 is private variable

15 Unit III: Functions and Strings FE PPS 2024


def display(self):
print("From class method var1=", self.var1) # var1 is accessible within class
print("From class method var2=", self. var2) # var2 is accessible within class
obj=ABC(10,20)
obj.display()
print("From main module, var1 =", obj.var1) # var1 is public, accessible outside class
print("From main module, var2 =", obj. var2) #Will give Error as var2 is private
Output:
From class method var1= 10
From class method var2= 20
From main module, var1 = 10
Error Message displayed

As a good programming habit, you should never try to access a private variable from anywhere
outside the class.
But if for some reason, you want to access the private variables outside the class, use following
Syntax:
objectName._className privatevariable
So to remove error from above code, you shall write last statement as print("From main module, var2
=", obj._ABC var2)

Private Methods:
We know that private attributes should not be accessed from anywhere outside the class.
Similarly, you can have private methods in your class. Which are accessible only within the
class.

class ABC:
def init (self, var1, var2):
self.var1 = var1 # var1 is public variable
self. var2= var2 # var2 is private variable

16 Unit III: Functions and Strings FE PPS 2024


def update(self, var1): #Public Method
self.var1 = var1 # var1 is accessible within class
self. display() #Accessing private method within the class

def display(self): #Private Method


print("From class method var1=", self.var1)
print("From class method var2=", self. var2)

obj=ABC(10,20) # Creating obj as object of class ABC


obj.update(30) # Accessing public method outside the class
obj._ABC display() #Accessing private method outside the class

Output:
From class method var1= 30
From class method var2= 20
From class method var1= 30
From class method var2= 20

5.8 Built in Function to check

5.8.1 Get

getattr(obj, attr, default=None)

 Used to retrieve the value of an attribute from an object.


 If the attribute does not exist:
o It raises an AttributeError if no default is specified.
o Returns the provided default value if specified.

Example:

class Person:
17 Unit III: Functions and Strings FE PPS 2024
def __init__(self):

self.name = "John"

self.age = 30

# Create an object

person = Person()

# Get the value of an existing attribute

print(getattr(person, 'name')) # Output: John

# Try to get a non-existent attribute with a default value

print(getattr(person, 'height', 'Not Specified')) # Output: Not Specified

# Try to get a non-existent attribute without default (raises AttributeError)

# print(getattr(person, 'weight')) # Uncomment to see the error

5.8.2 Set

setattr(obj, attr, value)

 Used to set the value of an attribute on an object.


 If the attribute does not exist, it creates a new one.

Example:

class Person:
def __init__(self):
self.name = "John"

18 Unit III: Functions and Strings FE PPS 2024


# Create an object
person = Person()

# Set a new value to an existing attribute


setattr(person, 'name', 'Alice')
print(person.name) # Output: Alice

# Create a new attribute


setattr(person, 'age', 25)
print(person.age) # Output: 25

5.8.3 Delete

Python delattr() Function is used to delete an object attribute in Python. It takes two arguments, the
first one is the class object from which we want to delete, second is the name of the attribute which
we want to delete. We can use delattr() to remove an attribute dynamically at runtime in Python.

Syntax
delattr (object, name)
Parameters:
Object: An object from which we want to delete the attribute
name: The name of the attribute we want to delete

class Equation:
x=3
y = -8
z=5
l1 = Equation()
print("Value of x = ", l1.x)
print("Value of y = ", l1.y)
print ("Value of z = ", l1.z)

19 Unit III: Functions and Strings FE PPS 2024


delattr(Equation,'z')
print ("Value of x = ", l1.x)
print ("Value of y = ", l1.z)

Output
Value of x = 3
Value of y = -8
Value of z = 5
Value of x = 3
ERROR!
Traceback (most recent call last):
File "<string>", line 14, in <module>
AttributeError: 'Equation' object has no attribute 'z'

5.9 Garbage Collection

Garbage collection is a memory management technique used in programming languages to


automatically reclaim memory that is no longer accessible or in use by the application. It helps
prevent memory leaks, optimize memory usage, and ensure efficient memory allocation for the
program.
Generational Garbage Collection
When attempting to add an object to a reference counter, a cyclical reference or reference cycle is
produced. Because the object’s reference counter could never reach 0 (due to cycle), a reference
counter cannot destroy the object. Therefore, in situations like this, we employ the universal waste
collector. It operates and releases the memory used. A Generational Garbage Collector can be found
in the standard library’s gc module.
Automatic Garbage Collection of Cycles
Because reference cycles take computational work to discover, garbage collection must be a scheduled
activity. Python schedules garbage collection based upon a threshold of object allocations and object
deallocations. When the number of allocations minus the number of deallocations is greater than the
threshold number, the garbage collector is run. One can inspect the threshold for new objects (objects
in Python known as generation 0 objects) by importing the gc module and asking for garbage collection
thresholds:
20 Unit III: Functions and Strings FE PPS 2024
import gc

# get the current collection


# thresholds as a tuple
print("Garbage collection thresholds:",
gc.get_threshold())

Output:
Garbage collection thresholds: (700, 10, 10)

5.10 class methods

The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated
after your function is defined. The result of that evaluation shadows your function definition. A class
method receives the class as an implicit first argument, just like an instance method receives the
instance.
Syntax Python Class Method:
class C(object):
@classmethod
def fun(cls, arg1, arg2, ...):
....
fun: function that needs to be converted into a class method
returns: a class method for function.

 A class method is a method that is bound to the class and not the object of the class.
 They have the access to the state of the class as it takes a class parameter that points to the class
and not the object instance.
 It can modify a class state that would apply across all the instances of the class. For example, it
can modify a class variable that will be applicable to all the instances.

Example:

21 Unit III: Functions and Strings FE PPS 2024


class MyClass:
def __init__(self, value):
self.value = value

def get_value(self):
return self.value

# Create an instance of MyClass


obj = MyClass(10)

# Call the get_value method on the instance


print(obj.get_value())

# Output: 10

5.11 Static methods


A static method does not receive an implicit first argument. A static method is also a method that is
bound to the class and not the object of the class. This method can’t access or modify the class state.
It is present in a class because it makes sense for the method to be present in class.

Syntax Python Static Method:


class C(object):
@staticmethod
def fun(arg1, arg2, ...):
...
returns: a static method for function fun.

Example:
class MyClass:
def __init__(self, value):
self.value = value

22 Unit III: Functions and Strings FE PPS 2024


@staticmethod
def get_max_value(x, y):
return max(x, y)

# Create an instance of MyClass


obj = MyClass(10)

print(MyClass.get_max_value(20, 30))

print(obj.get_max_value(20, 30))

complete Implementation
# Python program to demonstrate
# use of class method and static method.
from datetime import date

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

# a class method to create a Person object by birth year.


@classmethod
def fromBirthYear(cls, name, year):
return cls(name, date.today().year - year)

# a static method to check if a Person is adult or not.


@staticmethod
def isAdult(age):
return age > 18

23 Unit III: Functions and Strings FE PPS 2024


person1 = Person('mayank', 21)
person2 = Person.fromBirthYear('mayank', 1996)

print(person1.age)
print(person2.age)

# print the result


print(Person.isAdult(22))

24 Unit III: Functions and Strings FE PPS 2024

You might also like