From 759248dd928ffd2eda42673d7235e8c5fc426b4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9=20=D0=92=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D1=82=D0=B8=D0=BD=D0=BE=D0=B2=D0=B8=D1=87=20?= =?UTF-8?q?=D0=96=D0=B5=D0=B1=D1=80=D0=B8=D0=BA=D0=BE=D0=B2?= Date: Wed, 24 Apr 2024 11:27:05 +0900 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20less7.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- less7.md | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 less7.md diff --git a/less7.md b/less7.md new file mode 100644 index 0000000..74ffeb0 --- /dev/null +++ b/less7.md @@ -0,0 +1,89 @@ +[Ссылка на урок](https://youtu.be/iJu8UnKAWfA?si=wCmaFZE5mC9lkV--) + +ООП в Python +class Product: + count = 0 + + # При инициализации объекта можно передать параметры + def __init__(self, price=0): + self.name = "" + self.price = price + Product.count += 1 + + def help(self): + print("Название товара:", self.name) + + def __del__(self): + Product.count -= 1 + print("Этот стол отправился в топку") + + def __str__(self): + return "Теперь я могу вывести цену: " + str(self.price) + + def __bool__(self): + return self.price > 0 + + def __eq__(self, other): + return self.price == other.price + + def __add__(self, other): + new_obj = Product() + if isinstance(other, Product): + new_obj.name = self.name + new_obj.price = self.price + other.price + return new_obj + + def __call__(self, *args, **kwargs): + print(args, kwargs) +Создание объекта + +table = Product() +table.name = "Стол" +table.price = 1500 +table.help() +Атрибуты класса в Python +# Атрибуты можно добавлять динамически +table.color = "красный" +print(dir(table)) +# И удалять тоже +del table.color +print(dir(table)) + +# Можно проверить сущестовование атрибута +print("Есть атрибут color", hasattr(table, "color")) +print("Есть атрибут name", hasattr(table, "name")) +# установить атрибут +setattr(table, "material", "дуб") +# удалить +delattr(table, "material") +# и получить +print(getattr(table, "name")) +Магические методы класса в Python +# Передача параметров при инициализации __init__(self, price=0) +table_2 = Product(3500) +print(table_2.price) +# Изменение представления объекта при распечатке __str__ +print(table_2) + +# Проверка объекта как булево __bool__ +table_2.price = 0 +if table_2: + print("Цена объекта > 0") +else: + print("Цена объекта = 0") + +# Сравнение объектов __eq__ +table_2.price = 1500 +if table == table_2: + print("Цена одинаковая") + +# сложение объектов __add__ +table_3 = table + table_2 +print(table_3) + +# Обращение к объекту как к функции __call__ +table_3(5, a=4) + +print(Product.count) + +[Вернуться на главную](readme.md) \ No newline at end of file