override a private property on a subclass in python

To override a private property on a subclass in python, you can define a property with the same name on the subclass and set its value. In python, private properties are defined using double underscores at the beginning of the property name.

Here's an example:

main.py
class Parent:
    __private_property = "parent_value"
    
class Child(Parent):
    __private_property = "child_value"
    
child_instance = Child()
print(child_instance._Parent__private_property) # output: "parent_value"
print(child_instance._Child__private_property) # output: "child_value"
293 chars
10 lines

In the example above, we have a Parent class with a private property __private_property. We then define a subclass Child that overrides this property by defining a new private property with the same name and a different value.

To access the private property of the parent and the overridden private property of the child, we use the name mangling technique by prepending the class name to the private property name with a single underscore.

Note that the double underscore notation is really just a convention in Python that is intended to discourage accessing a property directly from outside of the class. However, since it's not enforced and it can still be accessed through the name mangling technique, it is really just a preference.

gistlibby LogSnag