Python-Cheatsheet/less7.md

2.8 KiB

Ссылка на урок

ООП в 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)

Вернуться на главную