Search code examples
pythonsolid-principlesliskov-substitution-principle

Python understanding Liskov Substiution Principle


In this example, am I violating LSP? Since straight up replacing the last two lines with an instance of a subclass will give me an error(as wage isn't initialised)?

person_1 = Employee('Brad')
person_1.print_name()
@dataclass
class Person:
    name: str

    def print_name(self):
        print(self.name)
@dataclass
class Employee(Person):
    wage: int

person_1 = Person('Brad')
person_1.print_name()

If so, then how can there ever be a non-violation of LSP when extending the constructor of a class (aside from placing optional attributes thereafter)?.


Solution

  • LSP says, that if something is true for a Person object (e.g. it has a name, the name is a string, it can print its name), it must be also true for an Employee object. In other words, every Employee is also a Person.

    It does not state that an Employee object must be created the same way as a Person object. Every Employee is not only a Person. It has not only the name, but also a wage.


    The second question:

    If the Employee.print_name() method were redefined not to print the name, but for instance to return it as a string, that would break the principle.

    Note that breaking the LSP does not require a code change, for instance if the Person's name format were changed from e.g. "first_name last_name" to "last_name, first_name" in the Employee, and that would cause the program to give incorrect output.