OOP in Python
Pradeep Aryal M.Sc.
3/9/2024 OOP in Python 1
Procedural Programming
Procedural programming:
Writing programs made of functions that perform specific tasks
▪ Procedures typically operate on data items that are separate from the
procedures
▪ Data items commonly passed from one procedure to another
▪ Focus: to create procedures that operate on the program’s data
3/9/2024 OOP in Python 2
Object-oriented Programming
Object-oriented programming: focused on creating objects
Object: entity that contains data and procedures
▪ Data is known as data attributes and procedures are known as methods
▪ Methods perform operations on the data attributes
Encapsulation: combining data and code into a single object
Data hiding: object’s data attributes are hidden from code outside the object
▪ Access restricted to the object’s methods
▪ Protects from accidental corruption
▪ Outside code does not need to know internal structure of the object
3/9/2024 OOP in Python 3
Object-oriented Programming
Object reusability: the same object can be used in different programs
Example: 3D image object can be used for architecture and game
programming
3/9/2024 OOP in Python 4
Everyday example of an object
Data attributes: define the state of an object
Example: clock object would have second, minute, and hour data attributes
Public methods: allow external code to manipulate the object
Example: set_time, set_alarm_time
Private methods: used for object’s inner workings
3/9/2024 OOP in Python 5
Classes
Class: code that specifies the data attributes and methods of a particular type
of object
▪ Similar to a blueprint of a house or a cookie cutter
Instance: an object created from a class
▪ Similar to a specific house built according to the blueprint or a specific
cookie make based on cookie cutter
▪ There can be many instances of one class
3/9/2024 OOP in Python 6
Classes
3/9/2024 OOP in Python 7
Classes
The housefly and mosquito objects are instances of the Insect class
3/9/2024 OOP in Python 8
Class Definitions
Class definition: set of statements that define a class’s methods and data
attributes
Format: begin with class Class_name:
Class names often start with uppercase letter
Method definition like any other python function definition
self parameter: required in every method in the class – references the
specific object that the method is working on
Initializer method: automatically executed when an instance of the class is
created
▪ Initializes object’s data attributes and assigns self parameter to the object
that was just created
▪ Format: def __init__ (self):
▪ Usually the first method in a class definition
3/9/2024 OOP in Python 9
Class
Example
import random
def main():
class Coin: # Create an object from the Coin class.
def __init__(self): coin = Coin()
self.sideup = 'Heads'
# Display the side of the coin that is
# facing up.
def toss(self): print('This side is up:’,coin.getSideup())
if random.randint(0, 1) == 0:
# Toss the coin.
self.sideup = 'Heads'
print('I am tossing the coin ...')
else: coin.toss()
self.sideup = 'Tails'
# Display the side of the coin that is
#facing up.
def getSideup(self): print('This side is up:', coin.getSideup())
return self.sideup
3/9/2024 OOP in Python 10
Class Definitions
coin = Coin()
Actions caused by the Coin() expression
3/9/2024 OOP in Python 11
Class Definitions
To create a new instance of a class call the initializer method
Format: My_instance = Class_Name()
To call any of the class methods using the created instance, use dot notation
Format: My_instance.method()
Because the self parameter references the specific instance of the object,
the method will affect this instance
Reference to self is passed automatically
3/9/2024 OOP in Python 12
Hiding attributes and storing classes in
modules
An object’s data attributes should be private
To make sure of this, place two underscores (__) in front of attribute name
Example: __current_minute
NOTE: We are not going to hide the attribute, so do NOT place the
underscores (__)
Classes can be stored in modules
Filename for module must end in .py
Module can be imported to programs that use the class
3/9/2024 OOP in Python 13
The BankAccount Class
Class methods can have multiple parameters in addition to self
For __init__, parameters needed to create an instance of the class
Example: a BankAccount object is created with a balance
When called, the initializer method receives a value to be assigned to
a balance attribute
For other methods, parameters needed to perform required task
Example: deposit method amount to be deposited
3/9/2024 OOP in Python 14
The BankAccount Class
Example
class BankAccount:
def __init__(self, name, balance = 0.0):
self.name = name
self.balance = balance
def getBalance(self):
return self.balance
def setBalance(self, balance):
self.balance = balance
def withdraw(self, amount):
pass
def deposit(self, amount):
pass
3/9/2024 OOP in Python 15
The BankAccount Class
Example
def main():
ba1 = BankAccount('James')
print(ba1.getBalance())
ba2 = BankAccount('Jane', 100.50)
print(ba2.getBalance())
ba1.setBalance(111)
print(ba1.getBalance())
3/9/2024 OOP in Python 16
The __str__ method
Object’s state: the values of the object’s attribute at a given moment
__str__ method: displays the object’s state
▪ Automatically called when the object is passed as an argument to the
print function
▪ Automatically called when the object is passed as an argument to the str
function
3/9/2024 OOP in Python 17
Working with Instances
Instance attribute: belongs to a specific instance of a class
Created when a method uses the self parameter to create an attribute
If many instances of a class are created, each would have its own set of
attributes
3/9/2024 OOP in Python 18
Working with Instances
coin1 = Coin()
coin2 = Coin()
coin3 = Coin()
The coin1, coin2, and coin3 variables reference three Coin objects
3/9/2024 OOP in Python 19
Working with Instances
coin1.toss()
coin2.toss()
coin3 .toss()
The objects after the toss method
3/9/2024 OOP in Python 20
Accessor and mutator methods
Typically, all of a class’s data attributes are private and provide methods to
access and change them
Accessor (getter) methods: return a value from a class’s attribute without
changing it
Safe way for code outside the class to retrieve the value of attributes
Mutator (setter) methods: store or change the value of a data attribute
3/9/2024 OOP in Python 21
Passing objects as arguments
Methods and functions often need to accept objects as arguments
When you pass an object as an argument, you are actually passing a reference
to the object
The receiving method or function has access to the actual object
Methods of the object can be called within the receiving function or
method, and data attributes may be changed using mutator methods
3/9/2024 OOP in Python 22
Techniques for designing Classes
UML diagram: standard diagrams for graphically depicting object-oriented
systems
▪ Stands for Unified Modeling Language
General layout: box divided into three sections:
▪ Top section: name of the class
▪ Middle section: list of data attributes
▪ Bottom section: list of class methods
3/9/2024 OOP in Python 23
Techniques for designing Classes
General layout of a UML diagram for a class
Coin
sideup
__init__()
toss()
getSideup()
UML diagram for the Coin class
3/9/2024 OOP in Python 24
class Coin
3/9/2024 OOP in Python 25