call a private property on an instance of a class in python

Private properties in Python can be declared by prefixing the attribute name with two underscores __ (double underscore) at the beginning of the variable name. This makes it so that the attribute can only be accessed within the scope of the class.

To call a private property on an instance of the class, you can use the name mangling syntax which adds the class name as a prefix to the attribute name with double underscores.

Here is an example:

main.py
class MyClass:
    def __init__(self):
        self.__private_property = "Hello World"

my_instance = MyClass()
print(my_instance._MyClass__private_property) # Output: "Hello World"`
183 chars
7 lines

In this example, calling my_instance._MyClass__private_property outside of the class raises an AttributeError. However, name mangling allows us to access the private property by adding the class name as a prefix with the double underscore. The convention is to use a single underscore instead of the class name prefix to indicate that a property or method is intended to be private or protected respectively.

gistlibby LogSnag