add a private property to a class in python

To add a private property to a class in Python, we can use a naming convention that involves adding two leading underscores to the property name. This naming convention provides a form of name mangling that effectively makes the property private and prevents it from being accessed or modified outside the class.

Here's an example:

main.py
class MyClass:
    def __init__(self):
        self.public_prop = "Hello, world!"
        self.__private_prop = 10
    
    def get_private_prop(self):
        return self.__private_prop
    
    def set_private_prop(self, value):
        self.__private_prop = value
267 chars
11 lines

In the example above, we define a class MyClass with two properties: public_prop (which is a regular public property), and __private_prop (which is a private property).

To access the private property from outside the class, we need to define a getter and/or a setter method. In this case, we define get_private_prop and set_private_prop methods that allow us to get and set the value of the private property.

Here's an example of how to use the class:

main.py
obj = MyClass()
print(obj.public_prop)   # Output: Hello, world!

# Accessing the private property directly will raise an AttributeError
# print(obj.__private_prop)   # Raises AttributeError

# Instead, we should use the getter and setter methods to access the private property
print(obj.get_private_prop())   # Output: 10
obj.set_private_prop(20)
print(obj.get_private_prop())   # Output: 20
393 chars
11 lines

gistlibby LogSnag