Загрузка данных


Окей, без проблем — делаю все 40 заданий.

---

**Классы и объекты**

**1. Класс Dog**
```python
class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        print(f"Привет! Меня зовут {self.name}")

dog = Dog("Шарик")
dog.bark()
```

---

**2. Класс Point**
```python
import math

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def distance_to_origin(self):
        return math.sqrt(self.x ** 2 + self.y ** 2)

p = Point(3, 4)
print(p.distance_to_origin())  # 5.0
```

---

**3. Класс Book**
```python
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def info(self):
        return f"«{self.title}» — {self.author}"

b = Book("Мастер и Маргарита", "Булгаков")
print(b.info())
```

---

**4. Класс Circle**
```python
import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2

c = Circle(5)
print(c.area())
```

---

**5. Класс Student**
```python
class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def promote(self):
        self.grade += 1

s = Student("Иван", 2)
s.promote()
print(s.grade)  # 3
```

---

**Инкапсуляция, атрибуты и свойства**

**1. Person с get/set age**
```python
class Person:
    def __init__(self, age):
        self.__age = age

    def get_age(self):
        return self.__age

    def set_age(self, new_age):
        if new_age > 0:
            self.__age = new_age

p = Person(25)
p.set_age(30)
print(p.get_age())  # 30
```

---

**2. BankAccount**
```python
class BankAccount:
    def __init__(self, balance=0):
        self.__balance = balance

    def deposit(self, amount):
        self.__balance += amount

    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount
        else:
            print("Недостаточно средств")

    def get_balance(self):
        return self.__balance

acc = BankAccount(100)
acc.deposit(50)
acc.withdraw(30)
print(acc.get_balance())  # 120
```

---

**3. Property full_name**
```python
class Person:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name

    @property
    def full_name(self):
        return f"{self.first_name} {self.last_name}"

p = Person("Иван", "Иванов")
print(p.full_name)  # Иван Иванов
```

---

**4. Rectangle с приватными атрибутами**
```python
class Rectangle:
    def __init__(self, width, height):
        self.__width = width
        self.__height = height

    @property
    def width(self):
        return self.__width

    @width.setter
    def width(self, value):
        if value > 0:
            self.__width = value

    @property
    def height(self):
        return self.__height

    @height.setter
    def height(self, value):
        if value > 0:
            self.__height = value

r = Rectangle(5, 10)
r.width = 8
print(r.width, r.height)  # 8 10
```

---

**5. Temperature с fahrenheit**
```python
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius

    @property
    def fahrenheit(self):
        return self._celsius * 9 / 5 + 32

t = Temperature(100)
print(t.fahrenheit)  # 212.0
```

---

**Наследование**

**1. Animal, Dog, Cat**
```python
class Animal:
    def speak(self):
        print("...")

class Dog(Animal):
    def speak(self):
        print("Гав!")

class Cat(Animal):
    def speak(self):
        print("Мяу!")

Dog().speak()
Cat().speak()
```

---

**2. Vehicle, Car, Bike**
```python
class Vehicle:
    def __init__(self, speed):
        self.speed = speed

class Car(Vehicle):
    def info(self):
        print(f"Машина, скорость: {self.speed}")

class Bike(Vehicle):
    def info(self):
        print(f"Велосипед, скорость: {self.speed}")

Car(120).info()
Bike(30).info()
```

---

**3. Shape, Square, Circle**
```python
import math

class Shape:
    def area(self):
        return 0

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2

print(Square(4).area())   # 16
print(Circle(3).area())
```

---

**4. Employee, Manager**
```python
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

class Manager(Employee):
    def __init__(self, name, salary, department):
        super().__init__(name, salary)
        self.department = department

m = Manager("Анна", 80000, "IT")
print(m.name, m.department)
```

---

**5. Bird, Penguin**
```python
class Bird:
    def fly(self):
        print("Птица летит")

class Penguin(Bird):
    def fly(self):
        print("Пингвины не летают")

Bird().fly()
Penguin().fly()
```

---

**Переопределение функционала базового класса**

**1. Animal, Bird, Fish — move()**
```python
class Animal:
    def move(self):
        print("Животное движется")

class Bird(Animal):
    def move(self):
        print("Птица летит")

class Fish(Animal):
    def move(self):
        print("Рыба плывёт")

Bird().move()
Fish().move()
```

---

**2. Shape, Rectangle, Circle — area()**
```python
import math

class Shape:
    def area(self):
        return 0

class Rectangle(Shape):
    def __init__(self, w, h):
        self.w = w
        self.h = 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(3, 4).area())  # 12
print(Circle(5).area())
```

---

**3. Printer, ColorPrinter, LaserPrinter**
```python
class Printer:
    def print(self, text):
        print(f"Печать: {text}")

class ColorPrinter(Printer):
    def print(self, text):
        print(f"Цветная печать: {text}")

class LaserPrinter(Printer):
    def print(self, text):
        print(f"Лазерная печать: {text}")

ColorPrinter().print("Привет")
LaserPrinter().print("Привет")
```

---

**4. User, AdminUser — login()**
```python
class User:
    def __init__(self, name):
        self.name = name

    def login(self):
        print(f"{self.name} вошёл")

class AdminUser(User):
    def login(self):
        super().login()
        print("Администратор вошёл")

AdminUser("Иван").login()
```

---

**5. Vehicle, ElectricCar — start_engine()**
```python
class Vehicle:
    def start_engine(self):
        print("Двигатель запущен")

class ElectricCar(Vehicle):
    def start_engine(self):
        print("Электродвигатель запущен")

ElectricCar().start_engine()
```

---

**Атрибуты классов и статические методы**

**1. Counter с _count**
```python
class Counter:
    _count = 0

    def __init__(self):
        Counter._count += 1

    @classmethod
    def get_count(cls):
        return cls._count

Counter()
Counter()
Counter()
print(Counter.get_count())  # 3
```

---

**2. Math.is_prime()**
```python
class Math:
    @staticmethod
    def is_prime(n):
        if n < 2:
            return False
        for i in range(2, int(n ** 0.5) + 1):
            if n % i == 0:
                return False
        return True

print(Math.is_prime(7))   # True
print(Math.is_prime(10))  # False
```

---

**3. User с user_count**
```python
class User:
    user_count = 0

    def __init__(self, name):
        self.name = name
        User.user_count += 1

User("Иван")
User("Мария")
print(User.user_count)  # 2
```

---

**4. Math.pi()**
```python
import math

class Math:
    @classmethod
    def pi(cls):
        return math.pi

print(Math.pi())
```

---

**5. Car.is_valid_model()**
```python
class Car:
    _valid_models = ["Toyota", "BMW", "Honda"]

    @staticmethod
    def is_valid_model(model):
        return model in Car._valid_models

print(Car.is_valid_model("BMW"))    # True
print(Car.is_valid_model("Lada"))   # False
```

---

**Класс object. Строковое представление**

**1. Book — __str__ и __repr__**
```python
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __str__(self):
        return f"«{self.title}» — {self.author}"

    def __repr__(self):
        return f"Book('{self.title}', '{self.author}')"

b = Book("1984", "Оруэлл")
print(str(b))
print(repr(b))
```

---

**2. Point — print выводит «Точка (x, y)»**
```python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"Точка ({self.x}, {self.y})"

print(Point(3, 4))  # Точка (3, 4)
```

---

**3. User — __repr__**
```python
class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"User('{self.name}', {self.age})"

u = User("Иван", 25)
print(repr(u))
```

---

**4. Circle — __str__ с радиусом и площадью**
```python
import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def __str__(self):
        return f"Радиус: {self.radius}, Площадь: {math.pi * self.radius ** 2:.2f}"

print(Circle(5))
```

---

**5. Student — __str__**
```python
class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def __str__(self):
        return f"{self.name}, курс {self.grade}"

print(Student("Иван", 3))
```

---

**Перегрузка операторов**

**1. Vector2D — оператор +**
```python
class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector2D(self.x + other.x, self.y + other.y)

    def __str__(self):
        return f"({self.x}, {self.y})"

v1 = Vector2D(1, 2)
v2 = Vector2D(3, 4)
print(v1 + v2)  # (4, 6)
```

---

**2. Book — операторы < и == по year**
```python
class Book:
    def __init__(self, title, year):
        self.title = title
        self.year = year

    def __lt__(self, other):
        return self.year < other.year

    def __eq__(self, other):
        return self.year == other.year

b1 = Book("Книга A", 1990)
b2 = Book("Книга B", 2000)
print(b1 < b2)   # True
print(b1 == b2)  # False
```

---

**3. Vector2D — унарный минус**
```python
class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __neg__(self):
        return Vector2D(-self.x, -self.y)

    def __str__(self):
        return f"({self.x}, {self.y})"

v = Vector2D(3, -4)
print(-v)  # (-3, 4)
```

---

**4. Vector2D — умножение на скаляр ***
```python
class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __mul__(self, scalar):
        return Vector2D(self.x * scalar, self.y * scalar)

    def __str__(self):
        return f"({self.x}, {self.y})"

v = Vector2D(2, 3)
print(v * 4)  # (8, 12)
```

---

**5. Matrix — оператор @**
```python
class Matrix:
    def __init__(self, data):
        self.data = data

    def __matmul__(self, other):
        rows = len(self.data)
        cols = len(other.data[0])
        result = [[sum(self.data[i][k] * other.data[k][j]
                   for k in range(len(other.data)))
                   for j in range(cols)]
                   for i in range(rows)]
        return Matrix(result)

    def __str__(self):
        return "\n".join(str(row) for row in self.data)

a = Matrix([[1, 2], [3, 4]])
b = Matrix([[5, 6], [7, 8]])
print(a @ b)
```

---

**Абстрактные классы и методы**

**1. Shape — Rectangle и Circle**
```python
import abc, math

class Shape(abc.ABC):
    @abc.abstractmethod
    def area(self): pass

class Rectangle(Shape):
    def __init__(self, w, h):
        self.w = w
        self.h = 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(3, 4).area())
print(Circle(5).area())
```

---

**2. Animal — Dog и Cat**
```python
import abc

class Animal(abc.ABC):
    @abc.abstractmethod
    def speak(self): pass

class Dog(Animal):
    def speak(self):
        print("Гав!")

class Cat(Animal):
    def speak(self):
        print("Мяу!")

Dog().speak()
Cat().speak()
```

---

**3. Storage — FileStorage и ConsoleStorage**
```python
import abc

class Storage(abc.ABC):
    @abc.abstractmethod
    def save(self, data): pass

    @abc.abstractmethod
    def load(self): pass

class FileStorage(Storage):
    def __init__(self, filename):
        self.filename = filename

    def save(self, data):
        with open(self.filename, "w") as f:
            f.write(data)

    def load(self):
        with open(self.filename, "r") as f:
            return f.read()

class ConsoleStorage(Storage):
    def __init__(self):
        self._data = ""

    def save(self, data):
        self._data = data
        print(f"Сохранено: {data}")

    def load(self):
        print(f"Загружено: {self._data}")
        return self._data

cs = ConsoleStorage()
cs.save("Привет")
cs.load()
```

---

**4. Vehicle — Car и Bike**
```python
import abc

class Vehicle(abc.ABC):
    @abc.abstractmethod
    def start_engine(self): pass

class Car(Vehicle):
    def start_engine(self):
        print("Двигатель автомобиля запущен")

class Bike(Vehicle):
    def start_engine(self):
        print("Мотоцикл заведён")

Car().start_engine()
Bike().start_engine()
```

---

**5. Logger — FileLogger и ConsoleLogger**
```python
import abc

class Logger(abc.ABC):
    @abc.abstractmethod
    def log(self, message): pass

class ConsoleLogger(Logger):
    def log(self, message):
        print(f"[LOG] {message}")

class FileLogger(Logger):
    def __init__(self, filename):
        self.filename = filename

    def log(self, message):
        with open(self.filename, "a") as f:
            f.write(f"[LOG] {message}\n")

ConsoleLogger().log("Запуск программы")
```