Inheritance syntax
1class Animal: # Parent
2def sleep(self):
3print("Zzz...")
4class Dog(Animal): # Child
5def bark(self):
6print("Woof!")
Reuse code and behavior from a parent class by creating child classes that extend it with more specific functionality.
The child class reuses the parent, then adds or overrides.
Inheritance lets a child class acquire properties and methods from a parent class. The child can add its own new properties and methods, or override parent methods.
classDiagram
class Animal {
+sleep()
+eat()
+sound()
}
class Dog {
+bark()
+sound()
}
class Cat {
+sound()
}
Animal <|-- Dog
Animal <|-- Cat
A parent class "Animal" has sleep(), eat(), and sound(). A child class "Dog" inherits these but overrides sound() to bark. A child class "Cat" overrides sound() to meow. Code reuse at its best!