2024-04-24 11:29:19 +09:00
[Ссылка на урок ](https://youtu.be/v3U6SGj2l_Q?si=bOMRzo_OsgBnto0K )
2024-04-24 12:50:28 +09:00
### Наследование в Python ###
#### Создадим базовый класс “Справочник” ####
```python
2024-04-24 11:29:19 +09:00
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)
2024-04-24 12:50:28 +09:00
```
2024-04-24 11:29:19 +09:00
2024-04-24 12:50:28 +09:00
#### Создадим класс “Справочники” с инициализацией экземпляра класса необходимыми атрибутами объекта и наследуемся от класса “Справочник” ####
```python
2024-04-24 11:29:19 +09:00
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)
2024-04-24 12:50:28 +09:00
```
#### Создадим 2 класса “Товары” и “Партнеры”. О б а наследуются от “Справочники”. В классах добавляем необходимые реквизиты для этих видов и при необходимости переопределяем методы родительских классов. ####
```python
2024-04-24 11:29:19 +09:00
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 = ""
2024-04-24 12:50:28 +09:00
```
2024-04-24 11:29:19 +09:00
2024-04-24 12:50:28 +09:00
### Примеры создания экземпляров классов ###
```python
2024-04-24 11:29:19 +09:00
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()
2024-04-24 12:50:28 +09:00
```
2024-04-24 11:29:19 +09:00
2024-04-24 12:50:28 +09:00
### Пример вызова статического метода класса ###
```python
2024-04-24 11:29:19 +09:00
print(Catalog.search_by_ref('734235ee-b821-4467-a905-ffb5a86a2ab0'))
2024-04-24 12:50:28 +09:00
```
2024-04-24 11:29:19 +09:00
[Вернуться на главную ](readme.md )