Наслідування дозволяє створити новий клас на основі існуючого.
Дочірній клас отримує всі атрибути та методи батьківського, і може:
• Додавати нові атрибути та методи
• Перевизначати методи батька
super() — виклик методу батьківського класу.
Переваги:
• Повторне використання коду
• Розширення функціональності без дублювання
• Логічна ієрархія (Тварина -> Собака -> Пудель)
import math
class Shape:
def area(self): return 0
class Rectangle(Shape):
def __init__(self, w, h):
self.w, self.h = w, h
def area(self): return self.w * self.h
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self): return math.pi * self.r ** 2
print(Rectangle(4, 5).area())
print(f'{Circle(3).area():.2f}')
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f'{self.name}, {self.age} років')
def speak(self):
print(f'{self.name} видає звук')
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
def speak(self):
print(f'{self.name} каже: Гав-гав!')
def fetch(self):
print(f'{self.name} приніс м\'ячик!')
class Cat(Animal):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def speak(self):
print(f'{self.name} каже: Мяу!')
def purr(self):
print(f'{self.name} муркоче: мрр...')
dog1 = Dog('Рекс', 3, 'Вівчарка')
dog2 = Dog('Бобик', 5, 'Дворняга')
cat1 = Cat('Мурка', 2, 'рудий')
cat2 = Cat('Барсик', 4, 'сірий')
for animal in [dog1, dog2, cat1, cat2]:
animal.info()
animal.speak()
dog1.fetch()
cat1.purr()
class Employee:
def __init__(self, name, base_salary):
self.name = name
self.base_salary = base_salary
def total_salary(self):
return self.base_salary
def __str__(self):
return f'{self.name}: {self.total_salary():.0f} грн.'
class Manager(Employee):
def __init__(self, name, base_salary, bonus_percent):
super().__init__(name, base_salary)
self.bonus_percent = bonus_percent
def total_salary(self):
return self.base_salary * (1 + self.bonus_percent / 100)
class Developer(Employee):
def __init__(self, name, base_salary, projects):
super().__init__(name, base_salary)
self.projects = projects
def total_salary(self):
return self.base_salary + self.projects * 5000
team = [
Manager('Олексій', 100000, 20),
Manager('Олена', 120000, 15),
Developer('Діма', 90000, 3),
Developer('Маша', 95000, 2)
]
print('=== Зарплати команди ===')
for emp in team:
print(emp)