Python Glossary Русский

all Python 3OOPterm

Inheritance

inheritance

A child class inherits the attributes and methods of its parent. Overriding methods gives polymorphism.

Syntax

class Child(Parent): ...

The classic mistake is overriding __init__ in the child and forgetting super().__init__(...): the parent's setup never runs and its attributes never appear. Inheritance couples classes tightly, so when you only need another class's behavior, composition (holding an object as a field) is often more flexible than subclassing just to reuse code.

Examples

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return '...'
class Dog(Animal):
    def speak(self):
        return 'Woof!'
class Cat(Animal):
    def speak(self):
        return 'Meow!'
for a in [Dog('Rex'), Cat('Whiskers')]:
    print(a.name, a.speak())  # → Rex Woof! / Whiskers Meow!
print(isinstance(Dog('x'), Animal))  # → True
print(isinstance(Dog('x'), Cat))  # → False
print(issubclass(Dog, Animal))  # → True
# Дочерний класс добавляет атрибуты
class Vehicle:
    def __init__(self, brand):
        self.brand = brand
class Car(Vehicle):
    def __init__(self, brand, doors):
        super().__init__(brand)
        self.doors = doors
c = Car('Toyota', 4)
print(c.brand, c.doors)  # → Toyota 4
# Наследование встроенных классов
class MyList(list):
    def total(self):
        return sum(self)
ml = MyList([1, 2, 3, 4])
print(ml.total())  # → 10
print(ml[0])  # → 1 — всё поведение list сохранилось
# Поиск метода идёт по MRO
class A:
    def hello(self):
        return 'A'
class B(A):
    pass
class C(B):
    pass
print(C().hello())  # → A
print([k.__name__ for k in C.__mro__])  # → ['C', 'B', 'A', 'object']
# Переопределение с вызовом родителя
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
    def describe(self):
        return f'{self.name}: {self.salary}'
class Manager(Employee):
    def __init__(self, name, salary, dept):
        super().__init__(name, salary)
        self.dept = dept
    def describe(self):
        return super().describe() + f' [{self.dept}]'
print(Manager('Alice', 80000, 'IT').describe())  # → Alice: 80000 [IT]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy