dataclass Python

Содержание
Введение
Пример
Методы
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'

Article author: Andrei Olegovich

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

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: