Python Encapsulation
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

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.

[Image visualizing the concept of OOP Encapsulation: a capsule or safe protecting internal data (variables) while exposing controlled methods (getters/setters) to the outside]

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:

Rahul

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:

15000

Modifying Private Data (Setter Method)

To update private data, use a setter method. Setter methods can also validate values before saving them.

Example

Using a setter with validation:

15000 18000 Balance cannot be negative

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:

78 Pass

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 outside the class hierarchy

Example

Using a protected property:

Kiran 5000

Note: Protected members are not strictly enforced by Python—this is a naming convention to signal intent to other developers.

Private Methods

Just like properties, methods can also be made private using double underscores (__). Private methods can only be called from inside the class itself.

Example

Creating a private method:

15

Name Mangling in Python

Python internally modifies private names using a process called name mangling.

  • __value internally becomes _ClassName__value
  • This avoids accidental access and naming conflicts in subclasses

Example

Understanding name mangling:

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