Object Oriented Programming
with Python
Lecture 2
Topics to Cover
● Introduction to OOP - Motivation
● Classes & Objects
● Operator Overloading
● Iterator for Class
● Inheritance
● Abstract Classes
● Name Spaces
● Shallow Vs Deep Copying
Introduction
● What is Object Oriented Programming (OOP)?
○ It is an approach for modelling real-world things (e.g., car, house) and relations between things (e.g.
student and teacher, company and employee).
○ In other words, OOPs models real-world entities as software objects and governs relationship among
them.
● Why OOP is needed?
○ OOP aims to provide the following qualities to the software program
■ Robustness against failures
■ Adaptability – Large codes can be easily adapted to accommodate new changes
■ Reusability – Same code base can be re-used in multiple application with little effort
● How does OOP achieve these Goals?
○ Encapsulation – By binding data and methods together and limiting its access from outside.
○ Modularity – Different software components are divided into different functional units – Inheritance.
○ Abstraction – Providing a simple and intuitive interface while hiding the implementation details –
making it easier for others to understand and use the code - Abstract classes.
Software Development
1. Design
2. Implementation
3. Testing & Debugging
a. Top-down: stubbing
b. Bottom-up: unit testing
c. Debugger - breakpoints, print statements
The Code that is shielded in a conditional construct of the above form will be executed when Python
is invoked directly on that module, but not when the module is imported for use in a larger software
project.
Class Definitions
● A class serves as the primary means for abstraction in object-oriented
programming.
● A class consists of the following two components:
○ Methods or member functions
○ Attributes: Data members, fields or instance variables.
● A class should provide
○ Encapsulation - data members are nonpublic
○ Error Checking
○ Codes for testing a class methods
Classes & Objects
● Class is a blueprint for creating objects.
● It binds data and method together.
● __init__() is the constructor which is called when an object is
instantiated.
● Python does not support formal access control.
● It enforces data protection only by convention
○ Protected member names starts with single underscore
‘_’ .
○ Private data member names start with double
underscores ‘__’
Variables starting with __ give a error when we try to access them
Operator Overloading
● Operator overloading: Re-defining the behavior of standard operators and functions
for various user-defined objects.
The standard operator ‘+’ provides different
functionality for different operands.
A = Student1()
B = Student2()
Team = A+B ??
Operator Overloading through specially named methods
● The behaviour of standard operators and built-in functions in python
can be redefined for a new class using specially named methods :
Examples:
+ operator is overloaded by implementing a method named __add__
● Non-operator overload
str(foo) is overloaded for an object by implementing a method
foo.__str__().
An user-defined class ‘foo’ can be treated as bool variable by
implementing foo.__bool__() method.
● If a particular special method is not implemented in a user-defined
class, the standard syntax relies upon that method will raise an
exception.
E.g. : a+b will raise an error if __add__ is not defined.
Example: Operator overloading for a vector class ● Implied Methods: There are some operators that have default
definitions provided by Python, in the absence of special methods,
and there are some operators whose definitions are derived from
others:
For example, the __bool__ method, which supports the syntax if
foo:, has default semantics so that every object other than None is
evaluated as True.
However, if __len__ method is defined, then bool(foo) is interpreted
by default to be True for instances with nonzero length
Iterator for a Class Example: Creating a class iterator using
generator syntax
● An iterator for a collection provides one key
behavior - It supports a special method named
__next__ that returns the next element of the
collection, if any, or raises a StopIteration
exception to indicate that there are no further
elements.
● There are two ways to implement an iterator
○ Using the generator syntax: __next__
and __iter__
○ By defining __len__ and __getitem__
methods for the user-defined class.
Creating Class iterator using __len__
and __getitem__ function
● Re-implementation of Python’s range() function.
● It is possible to execute a for loop over a range.
Inheritance
● A natural way to organize various structural components of a
software package is in a hierarchical fashion. Base Class
Parent
● Similar abstract functions are grouped together in a General
Child
level-by-level manner.
● The abstraction goes from specific to more general as one Parent
traverses up the hierarchy.
Child
● Inheritance allows a new class called (subclass or child
class) to be defined based upon an existing class (base class,
parent class or superclass) as the starting point.
Specific
● A subclass may specialize an existing behaviour by providing
a new implementation that overrides an existing method.
● A subclass may also extend its superclass by
Providing brand new methods.
Example: Python’s hierarchy of Exception Types
Example: Credit Card Class
It has following functionality
● Create new account for customer
● Allows to fetch customer related data
● Expenses could be charged to the card
● User can make payment to maintain the card
balance.
● Expenses can not exceed the card limit
Example: Inherited Class - PredatoryCreditCard
This child class
- Inherits the constructor of parent class to create new
customers
- Modifies the behaviour of charging the card by levying $5 if
charge is denied.
- Modifies the card payment function by charging interest on
overdue balance.
Another Example of Inheritance: Progression
Base Class
- Produces a general sequence
- It uses generator syntax (__next__, __iter__ )
to provide iteration capabilities.
- Create 3 new child classes to extend the capability of
this base class
Progression
Arithemetic Geometric Fibonacci
Progression Progression Progression
Geometric Progression
Fibonacci Progression
Arithmetic Progression
● Each child class modifies the base class
constructor __init__()
● Modifies the _advance() method
Abstract Classes
•An abstract class can be considered as a blueprint or template for other classes.
•An abstract class is a class that contains one or more abstract methods.
•An abstract method is a method that has declaration but no implementation.
•Abstract classes can not be instantiated. It needs subclasses (child classes) to provide
implementation.
•Abstract classes are required for providing “Abstraction” or a simplified interface (API)
while hiding the underlying implementation.
•Python provides abstract classes by declaring abstract base class (ABC) which could be
inherited by other child classes.
we cannot create a object of abstract class but we can create children classes
@abstractmethod
makes it compulsory to
redefine method in child
class
Example 2
Example 1
•X inherits base class constructor for initialization
•X re-defines abstract method in base class
Namespaces & Object-Orientation
● A class namespace includes all declarations that
are made directly within the body of the class
definition.
●
Class Instance namespace
Class namespace of for a
namespace of
PredatoryCreditCard PredatoryCreditCard
CreditCard
object
Shallow & Deep Copying
● Different methods for copying data
○ Aliases
○ Shallow copy
○ Deep Copy
If pallette is changed, warmtone
changes as well. They share the same
memory location.
● We can add and remove elements from pallette without ● In deep copy, the new copy references its own
affecting warmtones. copies of those referenced by the original
version.
● But we can not edit a color instance from the pallette list. It will
affect the warmtone colors. ● It creates separate memory location for two
copies.
● Although they are distinct lists, there remains indirect aliasing,
for example, pallette[0] and warmtones[0] as aliases for the ● Both copies could be modified independently
same color instance. without affecting each other.
Summary
In this module, we covered the following:
● What is OOPs and why is it needed?
● How to create classes and objects?
● How to overload standard operators and functions for user-defined classes?
● How to structure programs through inheritance?
● How to create and use Abstract Classes?
● Difference between shallow and deep copying.