The before code violates Liskov because Ostrich cannot fly but inherits fly(), causing errors. The after code fixes this by changing the method to move(), which all birds can do differently, ensuring subclasses can replace the parent without breaking behavior.
### Before applying Liskov Substitution Principle (violating it):
class Bird:
def fly(self):
print("Flying")
class Ostrich(Bird):
def fly(self):
raise Exception("Ostriches can't fly")
def make_bird_fly(bird: Bird):
bird.fly()
ostrich = Ostrich()
make_bird_fly(ostrich) # Raises Exception unexpectedly
### After applying Liskov Substitution Principle (correct):
class Bird:
def move(self):
print("Moving")
class FlyingBird(Bird):
def move(self):
print("Flying")
class Ostrich(Bird):
def move(self):
print("Running")
def make_bird_move(bird: Bird):
bird.move()
ostrich = Ostrich()
make_bird_move(ostrich) # Prints "Running" safely
flying_bird = FlyingBird()
make_bird_move(flying_bird) # Prints "Flying" safely