💻 Практические примеры

⚡ Минимальный рабочий пример

class Animal:
    def speak(self):
        print("Some sound")


class Dog(Animal):
    def speak(self):
        print("Woof!")


for a in [Animal(), Dog()]:
    a.speak()

Пример 1. Базовое наследование

Дочерние классы получают поля и методы родителя.

class Employee:
    def __init__(self, name: str) -> None:
        self.name = name

    def work(self) -> None:
        print(f"{self.name} is working...")


class Programmer(Employee):
    pass


class Manager(Employee):
    pass


p = Programmer("Alice")
m = Manager("Bob")
p.work()  # Alice is working...
m.work()  # Bob is working...

Пример 2. Полиморфизм через переопределение

Один и тот же вызов work() ведёт себя по-разному.

class Programmer(Employee):
    def work(self) -> None:
        print(f"{self.name} is writing code...")


class Manager(Employee):
    def work(self) -> None:
        print(f"{self.name} is managing team...")


staff = [Programmer("Alice"), Manager("Bob"), Programmer("Bill")]
for person in staff:
    person.work()

Пример 3. super() в __init__

class Programmer(Employee):
    def __init__(self, name: str, language: str) -> None:
        super().__init__(name)
        self.language = language


p = Programmer("Alice", "Python")
print(p.name)       # Alice
print(p.language)   # Python

Пример 4. super() в обычном методе

class Employee:
    def work(self) -> None:
        print("Employee is doing general tasks.")


class Programmer(Employee):
    def work(self) -> None:
        super().work()
        print("Programmer is writing code.")


class Manager(Employee):
    def work(self) -> None:
        super().work()
        print("Manager is holding a meeting.")


for person in [Programmer(), Manager()]:
    person.work()
    print()

Пример 5. Цепочка наследования

class Person:
    def __init__(self, name: str) -> None:
        self.name = name
        print(f"Init Person: {self.name}")


class Employee(Person):
    pass


class Manager(Employee):
    def __init__(self, name: str, department: str) -> None:
        super().__init__(name)
        self.department = department
        print(f"Init Manager: {self.name} manages {self.department}")


m = Manager("Alice", "Development")
# Init Person: Alice
# Init Manager: Alice manages Development

Пример 6. isinstance

class Animal:
    pass


class Dog(Animal):
    pass


d = Dog()
print(isinstance(d, Dog))      # True
print(isinstance(d, Animal))   # True
print(isinstance(d, object))   # True
print(isinstance(d, str))      # False
print(isinstance(d, (str, int, Animal)))  # True

Пример 7. issubclass

class Employee:
    pass


class Programmer(Employee):
    pass


class BackendDeveloper(Programmer):
    pass


print(issubclass(Programmer, Employee))          # True
print(issubclass(BackendDeveloper, Programmer))  # True
print(issubclass(BackendDeveloper, Employee))    # True
print(issubclass(Employee, Programmer))          # False
print(issubclass(Employee, object))              # True

Как запустить в VS Code

  1. Создайте папку python-fundamentals-practice/lesson-71/.
  2. Создайте файл inheritance_review.py и скопируйте в него любой пример.
  3. Откройте терминал в VS Code (Ctrl + `).
  4. Активируйте виртуальное окружение: venv\Scripts\activate (Windows) или source venv/bin/activate (Mac/Linux).
  5. Запустите: python inheritance_review.py
Проверить по документации: примеры дополнены аннотациями типов, которых не было в исходном материале. Подробнее см. typing.