[go: up one dir, main page]

0% found this document useful (0 votes)
15 views32 pages

Unit 312

Uploaded by

245123742004
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)
15 views32 pages

Unit 312

Uploaded by

245123742004
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/ 32

Programming for Problem Solving Using Python MVSREC

MATURI VENKATA SUBBA RAO (MVSR) ENGINEERING COLLEGE


NADERGUL, HYDERABAD-501510
(Sponsored by Matrusri Education Society, Estd.1980)
An Autonomous Institution
Approved by AICTE & Affiliated to Osmania University, Estd.1981
ISO 9001:2015 Certified Institution, Accredited by NAAC
website: www.mvsrec.edu.in

COURSE MATERIAL

For

PROGRAMMING FOR PROBLEM SOLVING USING


PYTHON
Subject Code: U21ESN03CS
Class: B.E- First Year, Sem-2
Acad.Year: 2021-22 Even Semester

Notes prepared by
P. Phani Prasad
Assistant Professor,
Department of CSE,
MVSREC

B.E- First Year, Sem-2 Page: 1


Programming for Problem Solving Using Python MVSREC

UNIT-III

TOPICS COVERED
1. Principles of Object Oriented Programming
2. Classes and Objects
3. Creating classes and objects
4. Constructor method
5. Creating multiple objects
6. Class attributes and Data attributes
7. Encapsulation
8. Inheritance
a. Definition and usage
b. Types of inheritance
9. Polymorphism
a. Operator overloading
b. Method overloading
c. Method overriding
10. Data hiding
a. Public and private members
i. Public and private variables
ii. Public and private methods

B.E- First Year, Sem-2 Page: 2


Programming for Problem Solving Using Python MVSREC

1. Principles of Object Oriented Programming


What is Object Oriented Programming?
● In Python, object-oriented Programming (OOP) is a programming paradigm that
uses the concept of classes and objects.
● It aims to visualize the given problem as the real-world entities and implement
them programmatically.
● An entity means any real-world object that possesses some kind of structure,
information and behavior.
● For example, a car is a real-world entity. It has some structure, information and
behavior.
● Information about cars like name, price, modelno, mileage, color, owner,
seatingcapacity etc.
● Behavior means the operations of the car: sellingCar, buyingCar, hiringCar,
servicingCar, drivingCar etc.
● Like this, we can represent any real-world entities like student, person, employee,
book, house, company, vehicles, devices etc. using OOP.
● For every entity the data and operations will be different based upon their
structure.
● Using OOP, data and operations for a given entity can be grouped together as a
single unit.
Need of OOP:
a. Binding the data and operations of an entity together as a single unit.
b. Reusing the existing entity details many times by other entities
c. Resembling the multiple functionalities by a single entity
d. Protecting or securing the data of an entity from outside code and exposing only
the relevant data for the given application
e. Approach of solving the given problem is much efficient than structured and
procedure oriented programming
Principles of OOP:
An OOP has the following principles that the python language can implement.
a. Classes and Objects
b. Inheritance
c. Polymorphism
d. Data Encapsulation
i. Data hiding

B.E- First Year, Sem-2 Page: 3


Programming for Problem Solving Using Python MVSREC

2. Classes and Objects


What is a class:
A class is a logical representation of an entity that possesses a name, attributes and
methods together combined as a block of a single unit.
→ Class is a user-defined data type that acts as a blueprint or a prototype for representing
a given entity.
→ Class cannot execute directly by itself because it is just a logical design that visualizes
the model for an entity.
→ Every class has a set of attributes called data or properties or fields. The attributes
specify the information about that entity.
→ classes also have methods called functions or operations or behavior. Methods
describe the actions to be performed on that entity.
→ The attributes and methods together are called members of the class
→ Every class should have a name which specifies the entity.
See the below tabular representations of class for ‘car’ ,student entities

Entity Name: car Entity Name: student

Attributes: Attributes:
name,price,owner,mileage,color,seatcap name,rollno,marks,branch,college,gend
acity er,year,semester

Methods: Methods:
driveCar(), sellCar(), buyCar(), getStudentDetails(), addStudents(),
registerCar() removeStudents()

What is an object?
An object is an instance of a class or implementation of a class.
As a class cannot execute by itself, it requires an object to interpret the logical design of
the generated class.
→ For a generated class, there could be multiple objects that can be created.
→ Each object has its own memory that could interpret the class.
→ A user can interact with the class through its corresponding object. All the attributes
and methods of a class can be accessed by using the object of that class.
→ Consider the design of a house. To construct a house a blueprint is required. Using that
blueprint we can build multiple houses.
→ Here the blueprint will be a class and each outcome of the house is an object of that
blueprint.Below diagram shows the relation between class and object.

B.E- First Year, Sem-2 Page: 4


Programming for Problem Solving Using Python MVSREC

3. Creating classes and objects


→ In python, the keyword ‘class’ is used to create a class for an entity.
Syntax of the class:
class classname:
#attribute-1
#attribute-2
….
#attribute-N
#method-1
#method-2

#method-N
For example, let's take the ‘car’ as an entity. Then to represent the car class, we use below
class car:
#attributes
name=’BMW’
price=1000000
mileage=’23.5 kmph’
owner=’rahul’
#methods
def drive(self):
print(“driving the car”)

B.E- First Year, Sem-2 Page: 5


Programming for Problem Solving Using Python MVSREC

def sell(self):
print(“selling the car”)
def getDetails(self):
print(“details of the car”)
Syntax to create an object:
variable=classname()
Example for creating an object for class ‘car’:
obj=car()
Here car() is an object and obj is a reference variable of type car that refer to the address
of car object
→ Using ‘obj’ we can access all attributes and methods of class ‘car’. To access an
attribute or method dot operator is used as per below syntax.
Accessing an attribute of class:
referenceVariable.attributeName
Example:
print(obj.name) #accessing car name and printing
obj.mileage=’25.34kmph’ #updating car mileage
Accessing/Calling a method of a class:
referenceVariable.methodName()
Example:
obj.driveCar() #calling the method driveCar()
obj.sellCar() #calling the method sellCar()

Sample Program:
Write a program to create a class car with some attributes and methods and implement it.
Solution:

B.E- First Year, Sem-2 Page: 6


Programming for Problem Solving Using Python MVSREC

Output:

4. Constructor method
What is a constructor?
A constructor is a special method defined inside a class used to initialize the
attributes of the class for an entity.
→ In python, A method __init__() is used to define the constructor for a class
→ To create a constructor we use the following syntax
Syntax:
def __init__(self [,argument(s)]):
#statements
Note: Square brackets [] in the above syntax indicate that they are optional.

B.E- First Year, Sem-2 Page: 7


Programming for Problem Solving Using Python MVSREC

Example-1 (Constructor without arguments):


def __init__(self):
self.a=10
self.b=20
Example-2 (Constructor with arguments):
def __init__(self,x,y):
self.a=x
self.b=y

Properties of the Constructor:


→ In python, the name of the constructor must be __init__. It should not be any other
name.
→ Constructor method will be called automatically when an object is created for a class.
We do not need to call it specifically.
→ Only one constructor method should be defined inside a class. It may be with or
without arguments.
→ Constructor method must have “self” as a mandatory argument and this must be the
first argument.
Types of constructor:
In python we can use three types of constructors:
a) Default constructor
b) Non-argument constructor
c) Argument Constructor
a) Default constructor: When a class is defined, python will internally create one empty
constructor without body and arguments.
This constructor won't be visible to the user but implicitly it is assumed to be created.
When an object is created, then by default python invokes this constructor.
This constructor is valid till the user creates any argument or non-argument constructor.
Example:
class demo:
def display():
print(“display method”)
obj=demo() #demo object created and calls default constructor
In the above example,other than display(), __init__() also will be created implicitly.
b) Non-argument constructor: When a constructor is created without any arguments
other than self, then it is called Non-argument constructor.
→ When an object is created, this constructor will be called explicitly.
→ During object creation, we should not pass any actual parameters to invoke this
constructor.
Example:

B.E- First Year, Sem-2 Page: 8


Programming for Problem Solving Using Python MVSREC

class car:
def __init__(self):
print(“car object created”)
self.name=’BMW’
self.price=100000
def display(self):
print(“Name=”,self.name)
print(“Price=”,self.price)

obj=car() # object creation and calls __init__() method


obj.display()
In the above example , we create & initialize two attributes for the car object namely
self.name and self.price using __init__() method. The display() method prints those attributes on
invocation.
c) Argument constructor: An __init__() method with at least one argument other than
self is called Argument constructor.
This type of constructor allows passing values to the object attributes dynamically.
For multiple objects ,we can pass multiple values during object creation for initializing
attributes of a class.
Example:
class car:
def __init__(self,n,p):
print(“car object created”)
self.name=n
self.price=p
def display(self):
print(“Name=”,self.name)
print(“Price=”,self.price)

# below line creates object and calls __init__() method


obj=car(‘BMW’,10000)
obj.display()

What is a “self” parameter?


➔ “self'' is a special parameter that refers to the current object and its attributes.
➔ “self” is used to initialize and access the current object attributes and methods
within a class.
➔ Attributes and methods Outside the class cannot be accessed using self instead
they will be accessed by object’s reference variable.

B.E- First Year, Sem-2 Page: 9


Programming for Problem Solving Using Python MVSREC

Consider the below program which prints the address of an object using “self” and
reference variable.

Output:

Notice that both outputs are the same. So we conclude that self refers to the current object
within a class and a reference variable is used to refer to an object outside the class.
5. Creating multiple objects
In a python program, there could be many classes. Each class may contain many objects.
Once a class is defined with a set of attributes and methods, then we can create many
objects.
We can create many objects by either separate reference variables or store and refer them
using a list variable.
Example-1

B.E- First Year, Sem-2 Page: 10


Programming for Problem Solving Using Python MVSREC

Example-2 (Creating objects and referencing through a list variable for above
student class)

In the above example,mylist is a list which stores 3 student objects.


Using the above approach, object details can be read and initialized dynamically.
Note: Observe the below statements:
obj1=car()
obj2=car()
obj3=car()
….
objN=car()
Here, obj1,obj2,obj3, …objN are reference variables and car() is an object for the class
‘car’.
All objects will store inside heap memory and reference variables will store in stack
memory. Observe the below diagram that depicts this statement.

B.E- First Year, Sem-2 Page: 11


Programming for Problem Solving Using Python MVSREC

These two memory addresses can be viewed separately by using id() function and self
parameter. id() function will return stack address and self will return object’s heap
address.
Observe below code:

Output:

6. Class attributes and Data attributes


As we know from the function definitions, there are two types of variables. I.e local
variables and global variables.
But in OOP, based on classes and objects, a class can have two types of attributes.
a) Class attributes
➔ Attributes which are defined and initialized within a class but
outside the methods are called class attributes.
➔ These attributes are shared by all the objects of a class and any
object can modify these attributes.
➔ Also called class variables
➔ Will be created only once when a class is created
➔ Scope and lifetime of these attributes is more than the data
attributes.
➔ Can be accessed within a class using class name or self parameter
➔ Can be accessed outside a class using class name
➔ To modify the value of class attribute syntax is

B.E- First Year, Sem-2 Page: 12


Programming for Problem Solving Using Python MVSREC

classname.attribute=value
➔ We cannot modify the class attribute using a reference variable or
self variable.
Syntax to create class attribute:
class classname:
#class attributes

examples output

b) Data attributes
➔ Attributes which are defined and initialized within constructor or methods
of a class are called data attributes.
➔ Also called instance variables or object variables
➔ These variables should be created and accessed by using “self” parameter.
➔ For multiple objects, multiple data attributes will be created separately.
Assume a class has 5 data attributes and you have created 3 objects for this

B.E- First Year, Sem-2 Page: 13


Programming for Problem Solving Using Python MVSREC

class. Then the 5 data attributes will be created 3 times uniquely for each
object.
➔ Scope and lifetime of data attribute is valid between the creation and
deletion of an object
➔ Can be accessed within methods of a class using self parameter
➔ Can be accessed outside a class using a reference variable.
➔ To modify the value of data attribute inside a method syntax is
self.attribute=value
➔ To modify the value of data attribute inside a method syntax is
referenceVariable.attribute=value
➔ We cannot modify the data attribute using a class variable
➔ Data attributes once created can be accessed by all methods of a class
using the “self” parameter.
Syntax to create data attribute:
class classname:
def __init__(self):
#data attributes
def method(self):
#data attributes

Example Output

In this example name,price are data attributes of the class car. Two objects are created. So
name,price are created twice for each object.

B.E- First Year, Sem-2 Page: 14


Programming for Problem Solving Using Python MVSREC

7. Data Encapsulation
Wrapping or binding of the attributes and methods of an entity together as a single unit of
block is called Data encapsulation.
● Main aim of encapsulation is to avoid exposure of sensitive data to the outside
class and restrict the users outside of class from modifying it.
● For an application, data for attributes is taken and retrieved methods of class.
Methods are the mediators between the user and sensitive data attributes.
● Example of data encapsulation is creating a class with a set of attributes and
methods. Attributes and methods are binded as a single unit of block called class.
● Data can be restricted by securing it as private variable.
● Example:
class employee:
def __init__(self):
self.name=’ram’
self.salary=50000
self.company=’microsoft’
def display(self):
print(self.name,self.salary,self.company)
8. Inheritance
a. Definition and usage
➔ Inheritance is the ability of acquiring the members from one class to
another class.
➔ Class from which members are borrowed or acquired is called super class
or parent class or base class or generalized class
➔ Class into which members are received or acquired is called sub class or
child class or derived class or specialized class
➔ Main use of inheritance is “Reusability of existing classes by many classes
many times” instead of rewriting the code from scratch by the inheriting
users.
➔ Represent an “is-a” relationship between parent and child classes. For
example, a student class could inherit a few members from another class
person. So here Student is-a person, shows an “is-a” relationship between
person and student classes.
Points to Remember:
➔ Always we create objects for child classes to access the entire code.
➔ Child class can access both parents and the child's members but the parent
class cannot.
➔ Here inheriting members means both attributes and methods of parent
class.

B.E- First Year, Sem-2 Page: 15


Programming for Problem Solving Using Python MVSREC

Syntax to apply inheritance between two classes:


class parent:
#parent attributes
#parent methods
class child(parent):
#parent attributes
#child attributes
#parent methods
#child methods

Example Output

b. Types of inheritance
We can inherit the members from one class to another class using the following
ways of inheritance.
i) Single-level inheritance : Inheriting the members from one parent class to
another one child class. Below figure depicts it. A is the parent class and B is the
child class.Object is created for child class.

Syntax:
class A:
#A’s attributes
# A’s methods
class B(A):
#B’s attributes
# B’s methods

B.E- First Year, Sem-2 Page: 16


Programming for Problem Solving Using Python MVSREC

Example output

ii) multilevel inheritance: Inheriting the members from one parent class to first
child class and first child class to second child class and so on.. Below figure
depicts it. A is the parent class and B is the first child class, C is the second child
class and Leaf is the last child class. Object is created for leaf class.

Syntax:
class A:
#A’s attributes, methods
class B(A):
#B’s attributes, methods


class N(N-1):
#N-1’s
attributes,methods

Example Output

B.E- First Year, Sem-2 Page: 17


Programming for Problem Solving Using Python MVSREC

10
20
30

iii) multiple inheritance : Inheriting the members from more than one parent
class by a single child class. Object is created for child class.

Syntax:
class A:
#A’s attributes,methods
class B:
#B’s attributes,methods
class C:
#C’s attributes,methods
….
class Z:
#Z’s attributes,methods
class subclass(A,B,C,...Z):
#subclass attributes,methods

Example Output

B.E- First Year, Sem-2 Page: 18


Programming for Problem Solving Using Python MVSREC

10
20
30

iv) hierarchical inheritance: Inheriting the members from one parent class by
many child classes. Objects will be created for all child classes.

Syntax:
class A:
#A’s attributes,methods
class B(A):
#B’s attributes,methods
class C(A):
#C’s attributes,methods
….
class Z(A):
#Z’s attributes,methods

Example Output

B.E- First Year, Sem-2 Page: 19


Programming for Problem Solving Using Python MVSREC

10
20
10
30

v) Diamond inheritance: Inheriting the members from two child classes which
are already inherited from a single parent class.
An ambiguity may arise between two child classes accessing a common member
from a parent class.
A precise decision will be applied by the python implicitly using a mechanism
called MRO (Method Resolution Order) to inherit the exact members from a
class.
What is MRO?
MRO (Method Resolution Order) is a mechanism of identifying the exact parent
class to be inherited by a child class.
It uses Depth-First Search technique from left-to-right order of inheritance applied
to the child class.

MRO for this inheritance will be


1) D inherits B
2) B should inherit either C or A. But as per MRO
policy, B inherits C
3) C inherits A
4) A inherits Object

Here D is the last child class inheriting both classes B,C


From left-to-right ,D comes first,next B, next C

B.E- First Year, Sem-2 Page: 20


Programming for Problem Solving Using Python MVSREC

Syntax:

class A:
#A’s attributes,methods
class B(A):
#B’s attributes,methods
class C(A):
#C’s attributes,methods
class D(B,C):
#D’s attributes,methods

Example Output

10
20
30
40

vi) Hybrid inheritance: Combination of any of the above two or more


inheritances.
There is no specific structure for this inheritance.

B.E- First Year, Sem-2 Page: 21


Programming for Problem Solving Using Python MVSREC

Syntax:
class A:
#A’s members
class B(A):
#B’s members
class C(B):
#C’s members
class D(B):
#D’s members
class E(C):
#E’s members
class F(D):
#F’s members
class G(D):
#G’s members

Example Output
class A: 10
a=10 20
class B(A): 30
b=20 50
class C(B): 10
c=30 20
class D(B): 40
d=40 60
class E(C): 10
e=50 20
def show(self): 40
print(self.a) 70
print(self.b)
print(self.c)
print(self.e)
class F(D):
f=60
def show(self):
print(self.a)
print(self.b)
print(self.d)
print(self.f)
class G(D):
g=70
def show(self):
print(self.a)

B.E- First Year, Sem-2 Page: 22


Programming for Problem Solving Using Python MVSREC

print(self.b)
print(self.d)
print(self.g)
obj1=E()
obj2=F()
obj3=G()
obj1.show()
obj2.show()
obj3.show()

9. Polymorphism
Definition: The ability to perform multiple tasks by an operator or method in different
contexts of the program.
The word polymorphism derived from two words poly (which means many) and
morphism (means change to different forms).
There are some operators which behave differently at different situations of the program.
For example, operator ‘+’ can do two things: It performs addition between two numerics
and also performs concatenation between two strings ,two lists or sets etc.
As a user, we can provide a new operation for an operator or a method to behave
differently at a specified context.

a. Operator overloading
● If an operator can do more than one task at different contexts in a
program,then the operator is said to be overloaded.
● We can provide many definitions for an operator to behave differently at a
given context.
● Assume if two rectangles are to be added , then ‘+’ operator should be
defined in such a way that it should add lengths of two rectangles and
breadths of two rectangles.The result of operation will be another
rectangle.
● To overload any operator, we need to define the corresponding operator
method inside a class and provide the operator logic.
Python supports special built-in methods to overload the following operators.

Operator Built-in method to overload Syntax

+ __add__(self,other) def __add__(self,other):


#overloading statements

- __sub__(self,other) def __sub__(self,other):


#overloading statements

B.E- First Year, Sem-2 Page: 23


Programming for Problem Solving Using Python MVSREC

* __mul__(self,other) def __mul__(self,other):


#overloading statements

/ __truediv__(self,other) def __truediv__(self,other):


#overloading statements

// __floordiv__(self,other) def __floordiv__(self,other):


#overloading statements

** __pow__(self,other) def __pow__(self,other):


#overloading statements

< __lt__(self,other) def __lt__(self,other):


#overloading statements

> __gt__(self,other) def __gt__(self,other):


#overloading statements

<= __le__(self,other) def __le__(self,other):


#overloading statements

>= __ge__(self,other) def __ge__(self,other):


#overloading statements

== __eq__(self,other) def __eq__(self,other):


#overloading statements

!= __ne__(self,other) def __ne__(self,other):


#overloading statements

<< __lsheft__(self,other) def __lshift__(self,other):


#overloading statements

>> __rshift__(self,other) def __rshift__(self,other):


#overloading statements

& __and__(self,other) def __and__(self,other):


#overloading statements

| __or__(self,other) def __or__(self,other):


#overloading statements

^ __xor__(self,other) def __xor__(self,other):


#overloading statements
The user should define his logic in the above methods for that operator.
When an operator is applied,the corresponding method will be invoked implicitly
and returns the result.

B.E- First Year, Sem-2 Page: 24


Programming for Problem Solving Using Python MVSREC

Sample Program:
Write a program to read and add two rectangles using operator overloading.

Program Output

Explanation of the above program:

Step-1: Program execution begins from r1=rectangle(2,3) statement. This line creates first
rectangle and calls __init__() to initialize length and breadth for r1
Step-2: This line also creates second rectangle and initializes length and breadth for r2
Step-3: r3=r1+r2 . This line implicitly calls __add__(self,other) method to execute.
This statement is equivalent to r3=r1.__add__(r2)
‘self’ will refer to r1 and ‘other’ will refer to r2.
Computes the addition of r1 and r2 length , r1 and r2 breadth and stores resultant length
and breadth in the rectangle variable ‘t’. Now ‘t’ will be returned.
Step-4: Returned ‘t’ will be referred to by r3 which is a computed rectangle .
Step-5: Displaying all rectangles by calling display() method

B.E- First Year, Sem-2 Page: 25


Programming for Problem Solving Using Python MVSREC

Method signature:
A method signature specifies the following things to be observed while defining methods.
i) name of the method
ii) No. of parameters of the method
iii) type of parameters of the method
iv) sequence of parameters of the method
Method signature helps to compare and check if two methods are equal or not as per the above
specification.
b. Method overloading
A method is said to be overloaded if any other method is defined exactly with the
same name but with different numbers and types of parameters in a class.
➔ It is an ability to define more than one method with the same name to
perform multiple different operations.
➔ But in python, we cannot define another method with the same name more
than once.
➔ Because python is an interpreted based language, only the last defined
method will be considered and previous methods will be discarded.
➔ So to achieve this method overloading, we define only one method which
needs to be overloaded with a maximum number of formal arguments.
➔ After a method is defined, we can call the same method many times with
different numbers of actual parameters.
➔ Number of actual parameters should be <= maximum number of formal
arguments in method definition.

Example Output

B.E- First Year, Sem-2 Page: 26


Programming for Problem Solving Using Python MVSREC

Note: method overloading is not suitable to write always in python. Instead it is recommended to
use keyword arguments or variable length keyword arguments.

B.E- First Year, Sem-2 Page: 27


Programming for Problem Solving Using Python MVSREC

c. Method overriding
During inheritance, if a method defined in parent class and a method defined in
child class have exactly the same method signatures then the child class method is
said to be overriding the parent class method.
➔ While using inheritance, we create objects for child class. So by default
the child class method will be invoked when two method signatures are
the same between parent and child class methods.
➔ Parent class method will be invisible to call when a child class object is
created.
➔ To overcome this, we use the “super()” function.
➔ “super()” function : A “super()” function is used to refer to the parent class
and calls explicitly parent class methods.
➔ When the child class method overrides the parent class method, super()
function calls the parent class method explicitly.
Observe the below examples. First is without using super() and other is using with ‘super()’

Example-1 Output

Note: In the above example, parent’s compute not called as it was overridden by child’s
compute.

Example-2 output

B.E- First Year, Sem-2 Page: 28


Programming for Problem Solving Using Python MVSREC

Note: In the above example, parent’s compute also called using the super() function along with
child’s compute.
Differences between method overloading and method overriding:

Method overloading Method overriding

Methods must have same name but with Methods defined in parent and child class
different number of parameters must have same method signatures

Can implement with or without inheritance Cannot implement without inheritance

Used to add additional behavior to the To modify the behavior of the existing method
existing method

Require at least two classes one for parent and


No need of creating multiple classes,Single other for child
class is enough to implement

10. Data hiding


The ability of hiding the sensitive data or information and allowing only the relevant
information to the outside users of the program is called data hiding.
➔ It is a part of encapsulation in which attributes and methods are combined as a
single unit.
➔ Main aim of data hiding is to restrict important attributes and expose normal
attributes to outside users.
➔ To provide restriction to data, attributes or methods must be declared as private.

B.E- First Year, Sem-2 Page: 29


Programming for Problem Solving Using Python MVSREC

■ Public and private members


In python, one of the OOP principles is to secure and restrict the data to be exposed from
outside users.
Class contains both attributes and methods. Attributes are the data or information about
the entity. Methods are used to perform operations on that entity. Methods are also used
as mediators between attributes and users to set and get the data.
We can restrict both the attributes and methods to be accessed by users outside the class.
a. Public and private variables
➔ Words “public” and “private” denote the level of security and restriction to
access the attribute.
➔ public attributes are attributes which can be accessed by inside and outside
functions of the class.
◆ There is no restriction for public attributes. They can access
anywhere in the program.
◆ This is the least level of restriction to the data.
◆ It is recommended to use when some data needs to be accessed in
an entire program by any object.
◆ There is no specific notation to denote these types of members.
Just define any method or attribute starting without any digit or
special character.
◆ Example:
class demo:
def __init__(self):
self.a=10
def show(self):
print(self.a)
d=demo()
d.show()
d.a=20 #accessing ‘a’ outside class
d.show()
➔ Private attributes are attributes which can be accessed only within a class.
Outside class these attributes cannot be modifiable.
➔ To declare a data attribute as a private, define any attribute with double
underscore (__) in front of the attribute name.
➔ Double underscore denotes that it is a restricted attribute and cannot be
accessed and modified by outside class.
➔ Private attributes are the highest level of restriction.
➔ Example to declare a private variable and public variable.
◆ def show(self):
self.a=10 #here ‘a’ is a public data attribute

B.E- First Year, Sem-2 Page: 30


Programming for Problem Solving Using Python MVSREC

self.__b=20 #here ‘b’ is a private data attribute

Note: By default, all class attributes of a class are private attributes. They cannot modified
outside the class
Example Output

b. Public and private methods


Like attributes , we can restrict or allow the methods to be accessed from inside or
outside of a class.
Public methods:
Methods whose name first character is alphabet and are defined within a class are
called public methods.
These methods can be accessed and called anywhere in the program.
Private methods:
Methods which are defined with double underscore (__) within a class are called
private methods.
These methods can be accessed only within the class but cannot be accessed
outside the class or anywhere else in the program.

B.E- First Year, Sem-2 Page: 31


Programming for Problem Solving Using Python MVSREC

Observe the below examples of using both public and private methods

Example-1 output

show method

As show() is a public method ,it can be called from outside class

Example-2 output

As __show() is a private method, it cannot be called from outside class. Private


methods can be called only within the same class.

Example-3 output

show method

B.E- First Year, Sem-2 Page: 32

You might also like