الوراثة
تسمح الوراثة بإنشاء صنف انطلاقًا من صنف آخر: class Cat(Animal):. يحصل الصنف الابن (Cat) تلقائيًا على خصائص الصنف الأب (Animal) وتوابعه.
يمكن للصنف الابن إعادة تعريف تابع لتغيير سلوكه، مثل speak(). وباستخدام super() يمكنه استدعاء تابع الصنف الأب، مثل super().__init__(...) داخل مُنشئه.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Cat(Animal):
def speak(self):
return self.name + " says meow"
class Dog(Animal):
def speak(self):
return self.name + " says woof"
for pet in [Cat("Tom"), Dog("Rex")]:
print(pet.speak())