add a private static property to a class in python

To add a private static property to a class in Python, we can use the double underscore prefix '__' before the property name. This makes the property name private and inaccessible outside the class definition.

Here is an example code snippet that demonstrates this:

main.py
class MyClass:
    __my_property = "private static property"
    
    @staticmethod
    def my_method():
        print(MyClass.__my_property)

MyClass.my_method()   # Output: "private static property"
print(MyClass.__my_property)   # Error: "'MyClass' object has no attribute '__my_property'"
293 chars
10 lines

In this code, we have added a private static property __my_property to the MyClass class. We have also defined a static method my_method that uses this private property.

When we call the static method using MyClass.my_method(), it prints the value of the private property. However, when we try to access the private property directly using MyClass.__my_property, we get an error because private properties are only accessible within the class definition.

gistlibby LogSnag