Python Encapsulation

Python Encapsulation

Kishore V


Python Encapsulation

Encapsulation is an object-oriented programming concept that focuses on hiding internal data and allowing access only through controlled methods.

In Python, encapsulation:

    • Keeps data (variables) and behavior (methods) together inside a class

    • Restricts direct access to sensitive data

    • Protects objects from accidental misuse

This improves data safety, control, and maintainability.

Private Properties

Python allows you to make class properties private by using a double underscore (__) before the variable name.

Example

Create a private property inside a class:

Try it Yourself

Note:

Private properties cannot be accessed directly from outside the class.

Accessing Private Data (Getter Method)

To read a private value safely, you should create a getter method.

Example

Using a getter to access a private property:

Try it Yourself

Modifying Private Data (Setter Method)

To update private data, use a setter method.

Setter methods can also validate values before saving them.

Example

Try it Yourself

Why Encapsulation Is Important

Encapsulation offers several advantages:

    • Data Protection: Prevents unauthorized access

    • Validation: Ensures correct data values

    • Flexibility: Internal code can change without affecting users

    • Control: You decide how data is read or modified

Practical Encapsulation Example

Example

Encapsulating and validating marks in a class:

Try it Yourself

Protected Properties

Python uses a single underscore (_) as a convention for protected members.

Protected properties:

    • Are meant for internal use

    • Can still be accessed, but should not be used directly

Example

Using a protected property:

Try it Yourself

Note:

Protected members are not enforced by Python—this is a naming convention only.

Private Methods

Just like properties, methods can also be made private using double underscores.

Example

Creating a private method:

Try it Yourself

Private methods can only be called inside the class.

Name Mangling in Python

Python internally modifies private names using name mangling.

    • __value becomes _ClassName__value

    • This avoids accidental access and conflicts in subclasses

Example

Understanding name mangling:

Try it Yourself


Our website uses cookies to enhance your experience. Learn More
Accept !