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.

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

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

Example: Using a protected property

Kiran 5000

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

15

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

4321

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