Определите __dict__ в классе данных с слотамиPython

Программы на Python
Anonymous
Определите __dict__ в классе данных с слотами

Сообщение Anonymous »

Рассмотрим следующий пример:

Код: Выделить всё

from dataclasses import dataclass

@dataclass(slots=True)
class Circle:
radius:int = 2

@property
def myslots(self):
return self.__slots__

@property
def __dict__(self):
return self.__slots__

c = Circle()
print(c.myslots)
print(c.__dict__)
что приводит к:

Код: Выделить всё

❯ python test.py
('radius',)
Traceback (most recent call last):
File "/home/raffaele/Downloads/test.py", line 21, in 
print(c.__dict__)
^^^^^^^^^^
AttributeError: 'Circle' object has no attribute '__dict__'. Did you mean: '__dir__'?
Как определить свойство dict в классе данных с помощью slots=True?

Вернуться в «Python»