override a private static property on a subclass in python

In Python, private static properties (denoted by double underscore prefix) cannot be accessed directly outside the class they are defined in, including its subclasses. However, we can still override them by creating a new property with the same name in the subclass.

Here's an example:

main.py
class Parent:
    __my_prop = 10  # private static property

    @classmethod
    def get_my_prop(cls):
        return cls.__my_prop

class Child(Parent):
    __my_prop = 20  # override parent's property

print(Parent.get_my_prop())  # output: 10
print(Child.get_my_prop())   # output: 20
289 chars
13 lines

In this example, Parent has a private static property called __my_prop with a value of 10. We cannot access this property outside of the Parent class.

To override this property in Child, we create a new private static property with the same name and a different value (20 in this case). When we call Child.get_my_prop(), it retrieves the value of __my_prop from Child instead of Parent, resulting in an output of 20.

It's worth noting that this technique only works for overriding private static properties, and not instance variables or methods. Additionally, it's generally not recommended to override private properties, as they are meant to be inaccessible from outside the class for a reason.

gistlibby LogSnag