0% found this document useful (0 votes)
8 views

Lecture 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lecture 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

OOP in Python Eng.

Omar Yahya

Lecture 2

Encapsulation
The feature of wrapping up data (attributes) and methods associated with that data into a single
unit is called encapsulation in Python. In any other programming languages or Python, this unit
is a class.
For example, scooter parts like engine, brakes, wheels, and methods like start(), stop(),
accelerate() encapsulate together to form a scooter.
Similarly, a class is an example of encapsulation that combines data and methods together into a
single unit and hides their internal details from outside the world.
Another real-time example of encapsulation is a capsule. Essentially, a capsule encapsulates
several combinations of medicine. If combinations of medicine represent variables and methods,
then the capsule will act as a class and the entire process refers to encapsulation as shown in the
below figure.

Figure 1: Encapsulation in OOP Python.

1
OOP in Python Eng. Omar Yahya

Encapsulation is one of the fundamental principles of OOP. Data members of a class in


encapsulation are only accessible through its member functions. It preserves the data safe from
misuse and any external interference.
Thus, we can say that encapsulation is a programming technique that involves bundling the
attributes (variables) and methods (functions) of a class into a single unit (the class itself) and
controlling their access through the use of access modifiers and member functions only.

Benefits of Encapsulation
• Data hiding:
Encapsulation helps to maintain the integrity of an object's data by preventing external
modification.
• Easier to understand:
It reduces code complexity by hiding implementation details, making code easier to understand
and maintain.
• Code reusability:
Encapsulation enables code reuse by creating a public interface for a class that can be used by
other parts of the program.
• Improved maintainability:
It provides better control over the behavior of an object, as changes can be made to the
implementation without affecting the rest of the program.
• Better control over class attributes:
Encapsulation helps to prevent naming conflicts by restricting the scope of variables and methods
to the class where they are defined.

Abstraction in Python
Abstraction is used to hide the internal functionality of the function from the users. The users only
interact with the basic implementation of the function, but inner working is hidden. User is familiar
with that "what function does" but they don't know "how it does."
In simple words, we all use the smartphone and very much familiar with its functions such as
camera, voice-recorder, call-dialing, etc., but we don't know how these operations are happening
in the background. Let's take another example - When we use the TV remote to increase the
volume. We don't know how pressing a key increases the volume of the TV. We only know to press
the "+" button to increase the volume.
That is exactly the abstraction that works in the object-oriented concept.

2
OOP in Python Eng. Omar Yahya

Why Abstraction is Important?


In Python, an abstraction is used to hide the irrelevant data/class in order to reduce the complexity.
It also enhances the application efficiency. Next, we will learn how we can achieve abstraction
using the Python program.

Class Diagram
Class diagrams are a type of UML (Unified Modeling Language) diagram used in software
engineering to visually represent the structure and relationships of classes within a system i.e. used
to construct and visualize object-oriented systems.

Class: ITEM
Attribute:
Number
Cost
……….
Methods:
SetData()
GetData()
……….

Python Access Modifiers


In most of the object-oriented languages access modifiers are used to limit the access to the
variables and functions of a class. Most of the languages use three types of access modifiers, they
are - private, public and protected.
In Python, unlike some other object-oriented programming languages like Java or C++, there are
no keywords like public, private, or protected to explicitly define access levels for class members.
Just like any other object-oriented programming language, access to variables or functions can also
be limited in python using the access modifiers. However, Python does have a convention for
marking attributes and methods as public, protected, or private. Python makes the use of
underscores (_) to specify the access modifier for a specific data member and member function in
a class.
Access modifiers play an important role to protect the data from unauthorized access as well as
protecting it from getting manipulated. When inheritance is implemented, there is a huge risk for
the data to get destroyed(manipulated) due to transfer of unwanted data from the parent class to
the child class. Therefore, it is very important to provide the right access modifiers for different
data members and member functions depending upon the requirements. Python provides three
levels of access control:

3
OOP in Python Eng. Omar Yahya

1. Public Access Modifier.


2. Protected Access Modifier.
3. Private Access Modifier.

1. Public Access Modifier


The members of a class that are declared public are easily accessible from any part of the
program. All data members and member functions of a class are public by default.
Syntax: Public attributes and methods are accessible from anywhere, both inside and outside the
class.
Usage: By default, all attributes and methods in a Python class are public.

2. Protected Access Modifier


The members of a class that are declared protected are only accessible to a class derived from it.
Data members of a class are declared protected by adding a single underscore ‘_’ symbol before
the data member of that class.
Syntax: Protected attributes and methods are indicated by a single underscore prefix _.
Usage: These members are intended to be accessed only within the class and its subclasses.

3. Private Access Modifier


By declaring your data member private you mean, that nobody should be able to access it from
outside the class, i.e. strong you can’t touch this policy. Python supports a technique called the
name mangling.
Syntax: Private attributes and methods are indicated by a double underscore prefix __.
Usage: These members are only accessible within the class itself. Python performs name mangling
on private members, making them inaccessible from outside the class (No outside Access is
allowed).

Figure 2: Comparison of Access Modifiers in OOP.

4
OOP in Python Eng. Omar Yahya

Classes and Objects

Data Types
• Primitive Data Types:
Primitive data types are the most basic types of data. They are predefined by the programming
language and represent simple values. Primitive data types typically have a fixed size in memory,
and their values are stored directly. Ex: Byte, Int, Float, Double, Char, Boolean.
• Non-Primitive Data Types (User):
Non-primitive data types are more complex and can be composed of multiple primitive data types.
They are also known as reference types because they store references to the actual data rather than
the data itself. Non-primitive types are created by the programmer or provided by the language as
classes or interfaces. Ex: Class.

Classes
In Object-Oriented Programming (OOP) in Python, a class is a blueprint for creating objects. A
class encapsulates data (attributes) and behavior (methods) into a single entity, making it easier to
manage and manipulate data in a structured way.
• Attributes: The properties or data members of a class. They represent the state of an object.
Attributes can be variables that store data.
• Methods: Methods are functions defined within a class. They represent the behavior of the
objects. Methods can perform operations on the data.
To create a class in python we use the class key word followed by the class name. Class name
should generally follow the CamelCase convention:
• Class names should start with an uppercase letter.
• If the class name consists of multiple words, each word should start with an uppercase
letter, and there should be no underscores between the words.
• Class names should be descriptive and meaningful, reflecting the purpose or nature of the
class.

Defining a Class:
A class is defined using the class keyword, followed by the class name and a colon. The class
body contains attributes and methods.

class ClassName:
# Define Attribute and Methods here.(Class body)
...

5
OOP in Python Eng. Omar Yahya

Example:

class Car:
brand = "Toyota" # class attribute.

Objects
An object is an instance of a class. A class serves as a blueprint for creating objects, defining the
structure and behavior that the objects created from it will have. Objects are the central concept
in OOP, allowing programmers to model real-world entities in code.
After creatin the class (template) we will need to create an instance of it (object) to be able to
access its attributes. We use the dot ( . ) operator to access attributes and methods:

# Creating an object of the class


my_car = Car()
# Accessing and printing the brand attribute
print(my_car.brand) # Output=> Toyota

Example 1:
A Python program that prints the name on the screen using a class.

class Student:
name = "Omar Yahya"

# Creating an object of the class


student1 = Student()
# Print student information
print("Name: ", student1.name) #Output=> Name: Omar Yahya

Example 2:
Create a class that represents a student in the class and contains two variables: the student's name
and his age.

class Student:
name = "Ahmed"
age = 30

6
OOP in Python Eng. Omar Yahya

# Creating an object of the class


student1 = Student()
# Print student information
print("Student name:", student1.name)
print("Age: ", student1.age)
# ↓↓-Output-↓↓
#student name: Ahmed
#Age: 30

Example 3:
A program to create a simple class representing a phone containing two variables: the phone's
brand and its price.

class Phone:
brand = "Samsung"
price = 1000

# Creating an object of the class Phone


phone1 = Phone()

print("Phone brand:", phone1.brand) #output:


print("Phone price", phone1.price)
# ↓↓-Output-↓↓
# Phone brand: Samsung
# Phone price: 1000

7
OOP in Python Eng. Omar Yahya

Modify class variables


When working with object-oriented programming (OOP) in Python, you can easily modify
variables within a class after creating objects. This is done by accessing variables using the
’object.variable’ syntax and then assigning new values to them.

Example 4:

class Student:
name = "Ahmed"
age = 30

# Creating an object of the class


student1 = Student()
# Print original information
print("Student name:", student1.name)
print("Age: ", student1.age)

# Modify variables
student1.name = "Mohammed"
student1.age = "20"

# Print information after modification


print("Student name:", student1.name)
print("Age: ", student1.age)
# ↓↓-Output-↓↓
# student name: Ahmed
# Age: 30
# student name: Mohammed
# Age: 20

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy