OOP in Python
OOP in Python
ipynb - Colab
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
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
Imparative
Procedural
Functional
Declarative
Object oriented
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)
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
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
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
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
keyboard_arrow_down OOP
-- class
-- variables
-- method
-- object
-- properties
-- best practices
Reusability of code.
Easier debugging and maintenance.
Improved modularity and scalability.
keyboard_arrow_down Class
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 Student:
...
class Studen:
pass
print(Student)
<class '__main__.Student'>
print(type(Student))
<class 'type'>
x = 90
print(type(x))
<class 'int'>
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
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
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
Example
name
age
Example
first_name
last_name
keyboard_arrow_down Methods
instance method
decorator
class method
magic/danda 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)
keyboard_arrow_down 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()
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_()
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"Name:{self.name}, Age:{self.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
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
Name:John, Age:20
John is elder than Abel : False
keyboard_arrow_down Object
An instance of a class
Exmple
student1
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
Abel
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}"
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}"
print(student1)
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.
# 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 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
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
12
78.5
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
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