How to Create a Private Instance Attribute in Python?

Estimated read time 2 min read

In Python, you can create a private instance attribute by prefixing the attribute name with two underscores (__). This makes the attribute name “name-mangled”, meaning it is rewritten to include the class name, which makes it more difficult to access the attribute from outside the class. Here’s an example code snippet:

class MyClass:
    def __init__(self, x, y):
        self.__x = x
        self.__y = y
    
    def get_x(self):
        return self.__x
    
    def set_x(self, x):
        self.__x = x

# Example usage:
obj = MyClass(10, 20)
print(obj.get_x())   # Output: 10
obj.set_x(30)
print(obj.get_x())   # Output: 30
print(obj.__x)       # Throws an AttributeError

In this example, we define a MyClass class with two private instance attributes __x and __y. We initialize these attributes in the constructor method __init__().

We also define getter and setter methods get_x() and set_x() to access and modify the value of the __x attribute from outside the class.

We test the class by creating an object obj of type MyClass, and using the get_x() and set_x() methods to access and modify the value of the __x attribute. We also try to access the __x attribute directly, which throws an AttributeError because the attribute name is “name-mangled”.

You can modify this code to include more private attributes or to use different naming conventions for private attributes, such as a single underscore prefix or a suffix. Note that private attributes can still be accessed from outside the class using the name-mangled attribute name, but this is not recommended as it can break encapsulation and lead to unexpected behavior.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply