gpt4 book ai didi

python - 有没有一种方法可以使用带有默认字段和 __slots__ 的数据类

转载 作者:太空宇宙 更新时间:2023-11-03 15:38:59 24 4
gpt4 key购买 nike

我想将 __slots__ 放在具有默认字段的数据类上。当我尝试这样做时,出现此错误:

>>> @dataclass
... class C:
... __slots__ = ('x', 'y', )
... x: int
... y: int = 1
...
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: 'y' in __slots__ conflicts with class variable

有什么办法可以实现吗?

最佳答案

有,通过使用 @add_slots decorator by ericvsmith :

import dataclasses

def add_slots(cls):
# Need to create a new class, since we can't set __slots__
# after a class has been created.

# Make sure __slots__ isn't already set.
if '__slots__' in cls.__dict__:
raise TypeError(f'{cls.__name__} already specifies __slots__')

# Create a new dict for our new class.
cls_dict = dict(cls.__dict__)
field_names = tuple(f.name for f in dataclasses.fields(cls))
cls_dict['__slots__'] = field_names
for field_name in field_names:
# Remove our attributes, if present. They'll still be
# available in _MARKER.
cls_dict.pop(field_name, None)
# Remove __dict__ itself.
cls_dict.pop('__dict__', None)
# And finally create the class.
qualname = getattr(cls, '__qualname__', None)
cls = type(cls)(cls.__name__, cls.__bases__, cls_dict)
if qualname is not None:
cls.__qualname__ = qualname
return cls

用法:

>>> @add_slots
... @dataclass
... class C:
... __slots__ = ('x', 'y', )
... x: int
... y: int = 1

只要没有默认值,手动添加 __slots__ 就可以。您可以找到相关的 Github issue here

关于python - 有没有一种方法可以使用带有默认字段和 __slots__ 的数据类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53776316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com