Python-Cheatsheet/less8.md

81 lines
2.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

[Ссылка на урок](https://youtu.be/v3U6SGj2l_Q?si=bOMRzo_OsgBnto0K)
Наследование в Python
Создадим базовый класс “Справочник”
from random import randint
from uuid import uuid4
# Наследование
class Catalog:
def get_object(self):
print("Получаем из базы: {}".format(self.__class__.__name__))
def write(self):
print("Записываем в базу: {}".format(self.__class__.__name__))
def delete(self):
print("Удаляем из базы: {}".format(self.__class__.__name__))
@staticmethod
def search_by_ref(ref):
return "Ищем в базе по ссылке {}".format(ref)
Создадим класс “Справочники” с инициализацией экземпляра класса необходимыми атрибутами объекта и наследуемся от класса “Справочник”
class Catalogs(Catalog):
def __init__(self, description=''):
self.code = randint(1, 1000)
self.description = description
self.deletion_mark = False
self.ref = uuid4()
def __str__(self):
return "Код {} Наименование {} Ссылка {}".format(self.code, self.description, self.ref)
Создадим 2 класса “Товары” и “Партнеры”. Оба наследуются от “Справочники”. В классах добавляем необходимые реквизиты для этих видов и при необходимости переопределяем методы родительских классов.
class Products(Catalogs):
def __init__(self, description=''):
super(Products, self).__init__(description)
self.image = None
def write(self):
# Можно проверить на корректность введеных данных
if self.image is not None:
super().write()
else:
print("Обязательно добавьте изображение")
class Partner(Catalogs):
def __init__(self):
super(Partner, self).__init__()
self.inn = ""
self.kpp = ""
Примеры создания экземпляров классов
table = Products('Стол дуб')
print(table)
table.write()
table2 = Products()
table2.description = 'Стол сосна'
table2.image = 'Изображение'
print(table2)
table2.write()
ooo_mayak = Partner()
ooo_mayak.description = 'ООО Маяк'
ooo_mayak.inn = '123'
ooo_mayak.kpp = '465768'
print(ooo_mayak)
ooo_mayak.write()
Пример вызова статического метода класса
print(Catalog.search_by_ref('734235ee-b821-4467-a905-ffb5a86a2ab0'))
[Вернуться на главную](readme.md)