0% found this document useful (0 votes)
62 views8 pages

004 - OOP-Encapsulation and Data Hiding

The document discusses encapsulation and data hiding in Object-Oriented Programming (OOP), emphasizing the importance of bundling data and methods within classes to restrict direct access to an object's components. It outlines the differences between public and private attributes, the benefits of encapsulation and data hiding, and the use of getters and setters for controlled access to attributes. Additionally, it explains Python's conventions for defining public and private attributes and the use of the @property decorator for implementing getters and setters.

Uploaded by

rychristiann
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views8 pages

004 - OOP-Encapsulation and Data Hiding

The document discusses encapsulation and data hiding in Object-Oriented Programming (OOP), emphasizing the importance of bundling data and methods within classes to restrict direct access to an object's components. It outlines the differences between public and private attributes, the benefits of encapsulation and data hiding, and the use of getters and setters for controlled access to attributes. Additionally, it explains Python's conventions for defining public and private attributes and the use of the @property decorator for implementing getters and setters.

Uploaded by

rychristiann
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

OBJECT ORIENTED PROGRAMMING

Encapsulation and Data Hiding

ENCAPSULATION
Encapsulation is a fundamental concept in Object-Oriented Programming (OOP) that refers to bundling data (attributes)
and the methods (functions) that operate on that data into a single unit, which is typically a class. The idea is to restrict
direct access to some of an object’s components, which makes the object’s interface simpler and less prone to misuse.

In Python, encapsulation is achieved by defining classes with attributes and methods. The attributes are typically
encapsulated by marking them as private or protected, which restricts access to the internal state of the object and
enforces control over how that data is modified.

Example of Encapsulation:

Key Points:
• Public attributes and methods are accessible from outside the class.
• Private attributes and methods (prefixed with __) are not accessible directly from outside the class.
• Encapsulation ensures that an object’s internal state can only be modified through a well-defined interface (i.e.,
methods that allow controlled access to attributes).
Benefits of Encapsulation:
• Data Protection: Encapsulation ensures that data cannot be accidentally modified. By restricting direct access to
class attributes, you can ensure that changes to those attributes are made only through designated methods.
• Modularity and Maintenance: Encapsulation helps in creating modular programs where objects are self-
contained. This makes the program easier to modify and maintain because changes in one class don’t necessarily
affect other parts of the program.
• Hides Complexity: Encapsulation hides the internal details and complexity of how the object’s data is stored and
managed. Users of the object don’t need to know how the data is managed internally, they only interact with the
object’s methods.
DATA HIDING
Data hiding is a related concept where the internal object data (attributes) is hidden from outside the object and can only
be accessed through the object’s methods. Data hiding is often implemented using encapsulation, specifically through the
use of private and protected attributes.
Private attributes (prefixed with __) cannot be accessed or modified directly from outside the class.
Protected attributes (prefixed with _) can be accessed from within the class and its subclasses but are intended to
discourage direct access from outside the class.

Example of Encapsulation:

Key Points:
Public Attribute (account_number):
• Can be accessed and modified directly from outside the class.
Protected Attribute (_account_holder):
• Indicated by a single underscore (_). It suggests that this attribute should not be accessed directly from outside
the class, but it’s still technically accessible (i.e., it’s a convention and not enforced by Python). It is often used to
indicate that the attribute is for internal use or subclass use.
• The protected attribute is accessed and modified through the methods get_account_holder() and
set_account_holder().
Private Attribute (__balance):
• The private attribute is indicated by a double underscore (__), making it inaccessible from outside the class. It can
only be accessed or modified via methods such as get_balance(), deposit(), and withdraw().

Benefits of Data Hiding:


• Security: It prevents external code from modifying critical attributes directly, which can lead to unintended
behavior.
• Controlled Access: By using methods to control access to hidden attributes, data hiding allows for validation or
other logic to be applied before the data is accessed or modified.
• Flexibility: The internal implementation of attributes can be changed without affecting the external interface,
making it easier to refactor or improve the code later on.
Difference Between Encapsulation and Data Hiding:
• Encapsulation is a broader concept that includes bundling data and methods together inside a class and controlling
how they interact. It’s a structural aspect of OOP that enforces modularity.
• Data Hiding is a specific technique used in encapsulation to restrict direct access to certain attributes, ensuring
that they can only be accessed or modified via methods.

PUBLIC AND PRIVATE ATTRIBUTES


In Python's OOP, attributes (also known as fields or properties) define the data stored within an object. These attributes
can be either public or private, controlling the level of access to the data stored in an object.

1. Public Attributes
• Definition: Public attributes are accessible from anywhere—both inside and outside the class.
• Behavior: Any code (from inside or outside the class) can read and modify the value of a public attribute. This is
the default behavior in Python.
• Naming Convention: Public attributes are written as plain attribute names without any special prefixes.

Example:

In the example above, the attributes make and model are public. They can be accessed and modified directly from outside
the class, allowing external code to change the object's state.

2. Private Attributes
• Definition: Private attributes are meant to be hidden from outside access and are only accessible from within the
class. They protect the internal state of an object from being changed directly.
• Behavior: To make an attribute private, it is preceded by two underscores (__). This invokes Python's name-
mangling mechanism, which alters the attribute name to prevent direct access from outside the class.
• Naming Convention: Private attributes are prefixed with two underscores (__), which is Python's way of signaling
that the attribute should not be accessed directly from outside the class.
Example:

In this example:
• The attributes __make and __model are private and cannot be accessed directly from outside the class.
• To read or modify the private attributes, public methods get_make() and set_make() are provided. This allows for
controlled access and modification of the internal state, which is a key aspect of encapsulation.

Name Mangling in Python


When you define a private attribute with two underscores (e.g., __make), Python uses a name-mangling mechanism to
prevent direct access. Python internally changes the name of the private attribute by appending the class name, making it
harder to access or modify accidentally from outside the class.

For example, __make in the Car class is internally changed to _Car__make. However, you can technically access it using
this mangled name, though this is discouraged.

While this demonstrates that private attributes are not truly hidden, Python relies on the convention of using double
underscores to signal to developers that the attribute is intended to be private and should not be accessed directly.

3. Encapsulation with Public and Private Attributes


Public and private attributes are central to the concept of encapsulation—one of the key principles of OOP. Encapsulation
ensures that an object’s internal data is protected from unauthorized access or modification, allowing for controlled
interaction through public methods (getters and setters). This helps prevent unintended side effects and ensures data
integrity.
In this BankAccount example:
• The account_holder is a public attribute that can be accessed directly.
• The __balance is a private attribute, which can only be accessed or modified through public methods (deposit()
and get_balance()).

Summary of Key Differences

Attribute Type Naming Access Level Purpose


Public Attribute No underscore Accessible from anywhere Allows open access to the data.
prefix
Private Prefixed with __ Only accessible within the Protects sensitive data from external
Attribute class access.
By using public and private attributes effectively, Python enables developers to control access to the internal state of
objects, ensuring that the object’s data remains consistent and only modified in appropriate ways.
GETTERS AND SETTERS
In Object-Oriented Programming, getters and setters are methods used to control access to an object's attributes. They
allow for encapsulation, where direct access to attributes is restricted, and the methods handle how these attributes are
retrieved or modified. In Python, while direct access to attributes is possible, it's good practice to use getters and setters
to manage complex logic, validation, or when attributes need to be protected from unintended modifications.

1. Direct Access to Attributes (Without Getters and Setters)


By default, attributes in Python classes are public, meaning they can be accessed and modified directly without restrictions:

This approach works, but if you need to add validation, security, or manage how the attribute is set, you might want to use
getters and setters.

2. Using Getters and Setters


Getters and setters allow you to control access to attributes. In Python, these are usually defined as methods.
Example:
Let’s say we want to ensure that the age of a person is always a positive number.

In this example:
• Getter (get_age): Retrieves the _age attribute.
• Setter (set_age): Validates the input to ensure that age is always a positive number.
Notice that the attribute self._age uses a single underscore (_age). This is a Python convention that indicates the variable
should be treated as private (not accessed directly from outside the class).
3. Using property() in Python
Python provides a more concise and Pythonic way to define getters and setters using the built-in property() function or
the @property decorator. This way, you can access the attributes using the typical object.attribute syntax while still using
getter and setter methods behind the scenes.
Example with @property:

In this case:
• @property is used to define the getter for age.
• @age.setter is used to define the setter for age.
This approach makes the code more intuitive, as you don't need to explicitly call get_age() or set_age(). Instead, you access
and modify age directly, and Python handles the function calls internally.

4. Benefits of Getters and Setters


• Encapsulation: Getters and setters hide the internal representation of the attribute, preventing direct
modification.
• Validation: Setters can ensure that values assigned to attributes are valid.
• Control: You can control when and how attributes are accessed and modified.
• Read-only attributes: Getters can be used to create read-only attributes by omitting the setter method.

5. Read-only
Attributes
If you want to
make an
attribute read-
only, you can
define only a
getter and omit
the setter:
In this example, since there’s no setter defined for radius, it cannot be modified once set during object creation.
Summary
• Getters retrieve the value of an attribute.
• Setters allow you to control how an attribute's value is set, with options for validation and control.
• Using Python’s @property decorator makes getters and setters easier to implement and more intuitive to use.

You might also like