override a public property on a subclass in python

To override a public property on a subclass in Python, you can simply define the property with the same name in the subclass and implement it as desired. Let's take an example to demonstrate how it works:

main.py
class Person:
    def __init__(self, name):
        self.name = name

    @property
    def description(self):
        return f"I am a person and my name is {self.name}"

class Student(Person):
    def __init__(self, name, student_id):
        super().__init__(name)
        self.student_id = student_id

    @property
    def description(self):
        return f"I am a student, my name is {self.name} and my id is {self.student_id}"
434 chars
17 lines

In the above code, we have defined a Person class with a public property description which returns a string describing the person. We have then defined a Student class which is a subclass of Person and overrides the description property with a new implementation that includes the student id in the description.

We can use these classes as follows:

main.py
person = Person("John")
print(person.description)  # prints "I am a person and my name is John"

student = Student("Jane", 123)
print(student.description)  # prints "I am a student, my name is Jane and my id is 123"
216 chars
6 lines

As you can see, the Student class overrides the description property defined in Person with its own implementation. Now, when we call description on an instance of Student, we get the student-specific description instead of the generic person description.

gistlibby LogSnag