dataclass Python

Contents
Введение
Пример
Методы
slots
Далее по теме

Введение

официальная документация

Предположим что мы к существующему класс Employee хотим добавить новый атрибут project, но не простой string, int и т.д. а отдельный кастомный класс.

class Employee: def __init__(self, name, age, salary, project): self.name = name self.age = age self.salary = salary

class Project: def __init__(self, name, payment, client): self.name = name self.payment = payment self.client = client def __repr__(self): return f"Project(name={repr(self.name)}, payment={repr(self.payment)}, client={repr(self.client)})" class Employee: def __init__(self, name, age, salary, project): self.name = name self.age = age self.salary = salary self.project = project p = Project("HeiHei.ru", 90000, "AndreyOlegovich.ru") e = Employee("Andrei", 36, 5000, p) print(e.project)

python dataclass_ex.py

Project(name='HeiHei.ru', payment=90000, client='AndreyOlegovich.ru')

Чтобы сократить шаблонный код , который объявлет класс Project используют dataclass

from dataclasses import dataclass @dataclass class Project: name: str payment: int client: str class Employee: def __init__(self, name, age, salary, project): self.name = name self.age = age self.salary = salary self.project = project p = Project("HeiHei.ru", 90000, "AndreyOlegovich.ru") e = Employee("Andrei", 36, 5000, p) print(e.project)

python dataclass_ex.py

Project(name='HeiHei.ru', payment=90000, client='AndreyOlegovich.ru')

Таким образом с помощью dataclass мы заменили

class Project: def __init__(self, name, payment, client): self.name = name self.payment = payment self.client = client def __repr__(self): return f"Project(name={repr(self.name)}, payment={repr(self.payment)}, client={repr(self.client)})"

на

from dataclasses import dataclass @dataclass class Project: name: str payment: int client: str

Методы

Датаклассы не ограничены только атрибутами. Можно создавать методы как и в обычных классах.

from dataclasses import dataclass @dataclass class Project: name: str payment: int client: str def notify_client(self): print(f"Notifying the client about the progress of the {self.name} development...") class Employee: def __init__(self, name, age, salary, project): self.name = name self.age = age self.salary = salary self.project = project p = Project("HeiHei.ru", 90000, "AndreyOlegovich.ru") e = Employee("Andrei", 36, 5000, p) p.notify_client()

Notifying the client about the progress of the HeiHei.ru development...

__slots__

Начиная с версии Python 3.10 в датаклассах можно ипользовать __slots__ для этого достаточно в декораторе dataclass указать slots=true

@dataclass(slots=True)

Без использования __slots__ к экземпляру класса можно добавлять новые атрибуты

from dataclasses import dataclass @dataclass() class Project: site: str manager: str p = Project("HeiHei.ru", "Andrey Olegovich") p.city = "Fuengirola" print(p.city)

Fuengirola

При использовании __slots__ этого делать нельзя. Подробности здесь .

from dataclasses import dataclass @dataclass(slots=True) class Project: site: str manager: str p = Project("HeiHei.ru", "Andrey Olegovich") p.city = "Fuengirola" print(p.city)

Traceback (most recent call last): File "C:\Users\Andrei\dataclass_slots.py", line 11, in <module> p.city = "Fuengirola" ^^^^^^ AttributeError: 'Project' object has no attribute 'city'

Related Articles
ООП в Python
Классы
Методы
class variables
class methods
Статические методы
Наследование
Специальные методы
dataclass
__slots__
Декоратор property
super()

Search on this site

Subscribe to @aofeed channel for updates

Visit Channel

@aofeed

Feedback and Questions in Telegram

@aofeedchat