""" Урок 72. Множественное наследование — весь код примеров одним файлом. Источник: subjects/python-fundamentals/course/lessons/72-multiple-inheritance/examples.html Файл собран автоматически (tools/build_lesson_examples.py): правьте страницу урока. Запуск: python lesson-72.py """ # ==================================================================== # Пример 1. Базовое множественное наследование # ==================================================================== class Printable: def print_info(self) -> None: print("Печать информации...") class Savable: def save(self) -> None: print("Сохраняем в файл...") class Report(Printable, Savable): pass report = Report() report.print_info() # Печать информации... report.save() # Сохраняем в файл... # ==================================================================== # Пример 2. Проверка атрибутов через hasattr # ==================================================================== class User: def __init__(self, username: str) -> None: self.username = username user = User("Alice") print(hasattr(user, "username")) # True print(hasattr(user, "email")) # False if hasattr(user, "email"): print(user.email) else: print("Поле email отсутствует") # ==================================================================== # Пример 3. Миксины для аутентификации и уведомлений # ==================================================================== class AuthMixin: def login(self) -> None: if not hasattr(self, "username"): raise AttributeError("Не задан username") print(f"{self.username} вошёл в систему.") def logout(self) -> None: print("Пользователь вышел из системы.") class NotificationMixin: def send_email(self, message: str) -> None: if not hasattr(self, "email"): raise AttributeError("Не задан email") print(f"Отправка письма на {self.email}: {message}") class UserProfile(AuthMixin, NotificationMixin): def __init__(self, username: str, email: str) -> None: self.username = username self.email = email user = UserProfile("alice", "alice@example.com") user.login() user.send_email("Добро пожаловать!") user.logout() # ==================================================================== # Пример 4. Порядок поиска методов # ==================================================================== class A: def greet(self) -> None: print("Hello from A") class B(A): pass class C: def greet(self) -> None: print("Hello from C") class D(B, C): pass d = D() d.greet() # Hello from A # ==================================================================== # Пример 5. Просмотр MRO через __mro__ # ==================================================================== class A: def greet(self) -> None: print("Hello from A") class B(A): def greet(self) -> None: print("Hello from B") class C(A): def greet(self) -> None: print("Hello from C") class D(B, C): def greet(self) -> None: print("Hello from D") print(D.__mro__) # (, , # , , # ) # ==================================================================== # Пример 6. super() в множественном наследовании # ==================================================================== class A: def action(self) -> None: print("A") class B(A): def action(self) -> None: print("B") super().action() class C(A): def action(self) -> None: print("C") super().action() class D(B, C): def action(self) -> None: print("D") super().action() d = D() d.action() # D # B # C # A # ==================================================================== # Пример 7. Композиция # ==================================================================== class ExitButton: def click(self) -> None: print("Выход из программы") class Menu: def __init__(self) -> None: self.exit_button = ExitButton() # композиция def show(self) -> None: print("Меню открыто") self.exit_button.click() menu = Menu() menu.show() # Меню открыто # Выход из программы # ==================================================================== # Пример 8. Агрегация # ==================================================================== class University: def __init__(self, name: str) -> None: self.name = name def get_info(self) -> None: print(f"Обучение проходит в университете: {self.name}") class Teacher: def __init__(self, name: str, university: University) -> None: self.name = name self.university = university # агрегация def introduce(self) -> None: print(f"Преподаватель: {self.name}") self.university.get_info() uni = University("Tech University") t1 = Teacher("Anna", uni) t2 = Teacher("Dmitry", uni) t1.introduce() t2.introduce() # ==================================================================== # Пример 9. Вложенный класс как композиция # ==================================================================== class Smartphone: class Battery: def __init__(self, capacity: int) -> None: self.capacity = capacity self.charge = capacity def use(self, amount: int) -> None: self.charge = max(self.charge - amount, 0) print(f"Батарея: {self.charge}/{self.capacity} мАч") def __init__(self, model: str, battery_capacity: int) -> None: self.model = model self.battery = self.Battery(battery_capacity) def play_video(self) -> None: print(f"{self.model} воспроизводит видео...") self.battery.use(300) phone = Smartphone("Pixel 9", 4000) phone.play_video()