Object-Oriented Programming
(OOP)
concepts in Python
What is Object-Oriented Programming in Python?
Object-Oriented Programming (OOP): is a programming paradigm that structures code by bundling
related properties (data) and behaviors (functions) into individual units called classes and objects.
This structure makes code easier to understand and modify, simplifies maintenance, and enhances scalability
as programs grow in size and complexity.
OOPs, Concepts in Python:
Class
Objects
Inheritance
Polymorphism
Encapsulation
Data Abstraction
1. Python Class
In Python, a Class is like an object constructor for creating objects.. Each class defines a type and describes the
attributes (data) and methods (functions) that every object created from that class will have.
Every value we create in Python is an object of some class, even basic data types like strings, numbers, and lists.
In this example: my_var is a variable that references an object.
The object type of my_var is str , which is a built-in class in python for string values.
Classes are created using the class keyword.
Each class includes a method called __init__(), automatically executed when a new object is instantiated.
This method initializes the object's attributes, defining its properties.
The self parameter within __init__() refers to the specific instance being created.
Instance attributes are unique to each object, allowing each instance to have its own set of attribute values.
2. Python Object
When an object of a class is created, the class is said to be instantiated. All instances share the same attributes and
behaviors defined by the class. However, the values of these attributes (e.g., the brand of a car) can be unique for each
instance. A single class can have any number of instances and methods that describe the behaviors of the objects
5
__str__() method
Python's __str__() method defines how a class object is represented as a string. It provides a human-readable
description, useful for logging and debugging.
3. Inheritance in Python
Inheritance allows a class to inherit attributes and methods from another class, promoting code reuse.
The child class can extend the parent's functionality. The super() function helps the child class (e.g., Motorcycle)
access methods and properties of the parent class (e.g., Cars).
Exercices: Python Inheritance
Task 1: Create a class named Student that will inherit properties and methods from a class named Person
Task 2: We have used the Student class to create an object named x. What is the correct syntax to
execute the printname method of the object x?
4. Polymorphism in Python
5. Encapsulation in Python
6. Data abstraction in Python