How to access private attributes in Python

Share Your Love

Private attributes in python are intended to be accessed and modified only within the class where they are defined.

However, Python provides a mechanism called name mangling that allows you to access private attributes from outside the class, although it is generally discouraged.

Name mangling modifies the name of the private attribute by adding a prefix of _ClassName to it, where ClassName is the name of the class. Here’s an example of how to access private attributes using name mangling:

class MyClass:
    def __init__(self):
        self.__private_var = 20   # Private attribute

    def __private_method(self):
        print("This is a private method")

obj = MyClass()

# Accessing private attribute using name mangling
print(obj._MyClass__private_var)   # Output: 20

# Accessing private method using name mangling
obj._MyClass__private_method()     # Output: This is a private method

In the above example, we access the private attribute __private_var and the private method __private_method using the name mangling syntax _ClassName__private_var and _ClassName__private_method, respectively.

However, it’s important to note that accessing private attributes directly from outside the class is generally discouraged and goes against the principle of encapsulation. Private attributes are intended for internal use within the class to ensure data protection and maintain class integrity.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter