1/15/25, 10:57 AM OOP in Python.
ipynb - Colab
keyboard_arrow_down Debre Berhan University
College of Computing
Department of Software Engineering
Principle of Programming
SEng 2021
01/15/2025
keyboard_arrow_down OOP
add Code add Text
keyboard_arrow_down Contents
Programming paradigms
Classes
Object
Four pillars of OOP
keyboard_arrow_down Learning Outcomes
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 1/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
Describe and implement object-oriented programming concepts such as classes, objects and
inheritance using python.
Demonstrate and apply the concepts and principles of Python programming language to real
world problems to develop a computer-based solution.
keyboard_arrow_down Introduction
Programming Paradigms
Programming paradigms is the way/style of writing a program
It is not refering to the specifice proramming language
Popular paradigms
Imparative
Procedural
Functional
Declarative
Object oriented
Imparative: step by step commanding a computer to do a specific task
Procedural: make code in a subroutines/procedures to improve modularity
Functional: Assing in avairable, pass as argument, returned from other function
Declarative: Hide the complexity and bringing programming language to human languge and
thinking.
OOP: Real wold entities coded as an object.
keyboard_arrow_down Imparative
numbers = [1,2,3,4,5,6,7,8,9,10]
sum = 0
for number in numbers:
if number == 8:
continue
else:
sum += number
print("Sum of the first ten integers except 8 =",sum)
Sum of the first ten integers except 8 = 47
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 2/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
keyboard_arrow_down Procedural
numbers = [1,2,3,4,5,6,7,8,9,10]
def add():
sum = 0
for number in numbers:
if number == 8:
continue
else:
sum += number
return sum
print("Sum of the first ten integers except 8 =",add())
Sum of the first ten integers except 8 = 47
keyboard_arrow_down Functional
numbers = [1,2,3,4,5,6,7,8,9,10]
def add():
sum = 0
for number in numbers:
if number == 8:
continue
else:
sum += number
return sum
print("Sum of the first ten integers except 8 =",add())
Sum of the first ten integers except 8 = 47
keyboard_arrow_down Declarative
Examples
filter()
map()
reduce()
sum()
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 3/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def add():
# Filter out the number 8
filtered_numbers = filter(lambda x: x != 8, numbers)
# Sum the filtered numbers
total_sum = sum(filtered_numbers)
return total_sum
print("Sum of the first ten integers except 8 =", add())
Sum of the first ten integers except 8 = 47
keyboard_arrow_down OOP
-- class
-- variables
-- method
-- object
-- properties
-- best practices
keyboard_arrow_down Benfites of OOP
Reusability of code.
Easier debugging and maintenance.
Improved modularity and scalability.
keyboard_arrow_down Class
It is a bluprint of an real-world object/entity
It is like a form/template for real-world object
It used to bundle propeties and methods
It is user defined data type
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 4/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
Syntax
class <name>:
properties
method/s
class is a keyword to start class
class name by convension it is a singular noun and if it is more than a word better to follow
pascal style
After a name colon(:) is followed
Then inside properites and methods could be defined when necessary and if not it can be
defined without them like below
Dot(.) is an operator used to access class members
class Student:
...
class Studen:
pass
print(Student)
<class '__main__.Student'>
print(type(Student))
<class 'type'>
x = 90
print(type(x))
<class 'int'>
Class with instance attributes
keyboard_arrow_down _init_() method
It is magic method used to set attributes of a class
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 5/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
It helps to pass data when an object is inistantiating
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
student1 = Student("John", 20) # object instansation
print("Name:",student1.name, ",Age:",student1.age)
student2 = Student("Abel", 22) # object instansation
print("Name:",student2.name, ",Age:",student1.age)
Name: John ,Age: 20
Name: Abel ,Age: 20
Class can be defined like this also, but it is not good practice
class Student:
first_name = None
last_name = None
student1 = Student()
student1.first_name = "John"
student1.last_name = "Doe"
print(student1.first_name, student1.last_name)
print("-"*50)
student2 = Student()
student2.first_name = "Abel"
student2.last_name = "Samuael"
print(student2.first_name, student2.last_name)
John Doe
--------------------------------------------------
Abel Samuael
keyboard_arrow_down Variables
Instance attribute/variable
Class attribute/variable
keyboard_arrow_down Instance variables
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 6/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
They are specific for an instance of a class
Example
name
age
keyboard_arrow_down Class Variable
They could be refered by a class directly
Example
first_name
last_name
keyboard_arrow_down Methods
They are functions in a class
They could be:
instance method
decorator
class method
magic/danda method
keyboard_arrow_down Instance method
These are the most common methods in a class, which operate on instance-level data.
They take self as the first parameter to access instance attributes and other instance
methods. However, the word self can be any name of the first parameter
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 7/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
def print_info(self):
print("Name:",self.name, ",Age:",self.age)
student1 = Student("John", 20) # object instansation
student1.print_info()
student2 = Student("Abel", 22) # object instansation
student2.print_info()
Name: John ,Age: 20
Name: Abel ,Age: 22
keyboard_arrow_down Decorator
A decorator in Python is a design pattern used to modify or enhance the behavior of a
function, method, or class without permanently changing its structure.
Decorators are applied using the @decorator_name syntax.
keyboard_arrow_down Class method
These methods operate on the class itself rather than an instance.
They take cls as the first parameter to access class attributes or modify the class state.
Defined using the @classmethod decorator.
class Student:
name = None
age = None
@classmethod
def print_info(cls):
print("Name:",cls.name, ",Age:",cls.age)
Student.name = "John"
Student.age = 20
Student.print_info()
Name: John ,Age: 20
keyboard_arrow_down Magic/dunda methods
Special methods in Python that start and end with double underscores (__).
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 8/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
They provide built-in behavior for custom objects, such as operator overloading and object
initialization.
examples _init_, _str_, _gt_
_str_()
It use to print string of an object
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Name:{self.name}, Age:{self.age}"
student1 = Student("John", 20) # object instansation
print(student1)
student2 = Student("Abel", 22) # object instansation
print("Name:",student2.name, ",Age:",student1.age)
Name:John, Age:20
Name: Abel ,Age: 20
_eq_()
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Name:{self.name}, Age:{self.age}"
def __eq__(self, other):
return self.age == other.age
student1 = Student("John", 20) # object instansation
print(student1)
student2 = Student("Abel", 22) # object instansation
print(student1.name, "is equal with", student2.name, ":", student1 == student2)
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 9/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
Name:John, Age:20
John is equal with Abel : False
_gt_()
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Name:{self.name}, Age:{self.age}"
def __gt__(self, other):
return self.age > other.age
student1 = Student("John", 20) # object instansation
print(student1)
student2 = Student("Abel", 22) # object instansation
print(student1.name, "is elder than", student2.name, ":", student1 > student2)
Name:John, Age:20
John is elder than Abel : False
keyboard_arrow_down Object
An instance of a class
Exmple
student1
keyboard_arrow_down Properties(getter and setter)
To make attributes private use _(underscor) or __(double underscore) as a convension
However, it does not prevent the propery from modified by a user
@property decorator is used for a getter
@<name>.setter for a setter
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 10/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
student1 = Student("John", 20) # object instansation
student1.name = "Abel"
print(student1.name)
Abel
keyboard_arrow_down Four pillars of OOP
1. Inheritance
It is a code reuse mechanism
There is a super/base/parent class which has some code defined and drived/sub/child class
that reused the code already defined in super/base/parent class
Syntax
class Base:
...
class Derived(Base):
...
class User:
def __init__(self, name, age):
self.name = name
self.age = age
class Student(User):
def __init__(self, name, age, student_id):
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 11/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
super().__init__(name, age)
self.student_id = student_id
def __str__(self):
return f"Name:{self.name}, Age:{self.age}, Student ID:{self.student_id}"
student1 = Student("John", 20, 12345)
print(student1)
Name:John, Age:20, Student ID:12345
class User:
def __init__(self, name, age):
if not name:
raise ValueError("Missing name")
if not age:
raise ValueError("Missing age")
self.name = name
self.age = age
class Student(User):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def __str__(self):
return f"Name:{self.name}, Age:{self.age}, Student ID:{self.student_id}"
name = input("Enter your name: ")
age = input("Enter your age: ")
student_id = input("Enter your student ID: ")
student1 = Student(name, age, student_id)
print(student1)
Enter your name: sdvsd
Enter your age: dvsd
Enter your student ID: dvsd
Name:sdvsd, Age:dvsd, Student ID:dvsd
keyboard_arrow_down Multiple inheritance
Not recommended
Syntax
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 12/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
class Base1:
...
class Base2:
...
class Derived(Base1, Base2):
...
2. Abstraction
It is the process of hiding implementation details and showing only essential features to the
user.
It is achieved in Python using abstract base classes (ABC) and the @abstractmethod
decorator.
from abc import ABC, abstractmethod
class Animal(ABC): # Abstract base class
@abstractmethod
def sound(self):
pass
class Dog(Animal): # Concrete class
def sound(self):
return "Bark"
class Cat(Animal): # Concrete class
def sound(self):
return "Meow"
# Usage
animals = [Dog(), Cat()]
for animal in animals:
print(animal.sound())
Bark
Meow
3. Encapsulation
It is the bundling of data and methods into a single unit (class) and restricting direct access to
some components using access modifiers (_ for protected and __ for private).
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 13/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def get_balance(self):
return self.__balance
# Usage
account = BankAccount(100)
account.deposit(50)
print(account.get_balance()) # 150
#print(account.__balance) # AttributeError: 'BankAccount' object has no attribute '__balanc
150
4. Polymorphism
It means "many forms."
It allows objects of different classes to be treated as objects of a common superclass. This is
achieved through method overriding and duck typing.
class Shape:
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
# Usage
shapes = [Rectangle(3, 4), Circle(5)]
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 14/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
for shape in shapes:
print(shape.area())
12
78.5
keyboard_arrow_down Best practices
Single responsibility principle
Open closed principle
Liskov substitution principle
Interface segregation principle
Dependency inversion principle
SOLID
keyboard_arrow_down Summary
Programming Paradigms: The document introduces different programming paradigms
including imperative, procedural, functional, declarative, and object-oriented.
It provides examples of imperative, procedural, functional and declarative paradigms.
Classes: A class is a blueprint for creating objects. It is a user-defined data type that bundles
properties and methods. The syntax for defining a class is class :. A class can be defined with
or without properties and methods.
The init() method helps to pass data when an object is instantiated.
Classes can have instance attributes, which are specific to an instance of a class.
Classes can also have class attributes, which can be referred to directly by the class.
Methods: These are functions within a class.
Instance methods operate on instance-level data and take self as the first parameter.
Class methods operate on the class itself and take cls as the first parameter. They are
defined using the @classmethod decorator.
Magic/dunder methods are special methods that start and end with double underscores
and provide built-in behavior for custom objects, such as init, str, eq, and gt.
Objects: An object is an instance of a class.
Properties: These are used to make attributes private using underscores (_ or __). The
@property decorator is used for a getter, and @<name>.setter is used for a setter.
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 15/16
1/15/25, 10:57 AM OOP in Python.ipynb - Colab
Four Pillars of OOP:
Inheritance: A mechanism for code reuse, where a derived/sub/child class inherits from
a super/base/parent class. The syntax is class Derived(Base):. The super() function can
be used to call methods from the parent class. Multiple inheritance is possible but not
recommended.
Abstraction: The process of hiding implementation details and showing only essential
features. This is achieved using abstract base classes (ABC) and the @abstractmethod
decorator.
Encapsulation: The bundling of data and methods into a single unit (class), restricting
direct access to some components using access modifiers (_ for protected and __ for
private).
Polymorphism: Allows objects of different classes to be treated as objects of a common
superclass through method overriding and duck typing.
Best Practices: The document mentions SOLID principles, including the single responsibility
principle, open-closed principle, Liskov substitution principle, interface segregation principle,
and dependency inversion principle
https://colab.research.google.com/drive/1jNuAXUpZJRMNkSzYdUueSZyMnpcteh2T#scrollTo=A-_H6w3SdLFu&printMode=true 16/16