gpt4 book ai didi

python - 如何删除数据类属性

转载 作者:行者123 更新时间:2023-12-04 11:24:03 25 4
gpt4 key购买 nike

我有一个这样的数据类:

@dataclass
class Bla:
arg1: Optional[int] = None
arg2: Optional[str] = None
arg3: Optional[Dict[str, str]] = None

我想要这种行为:
>>> bla = Bla(arg1=None, arg2=None, arg3=None)
>>> asdict(bla)
{'arg1': None, 'arg2': None, 'arg3': None}

>>> bla = Bla()
{}

在这种特定情况下,我可以使用 dict ,但我会失去类型提示的可能性(并使用 mypy)

所以我试过这个:
class none:
...

@dataclass
class Bla:
arg1: Union[none, int] = none()
arg2: Union[none, str] = none()
arg3: Union[none, Dict[str, str]] = none()

def __post_init__(self) -> None:
for k, v in self.__dict__.copy().items():
if isinstance(v, none):
delattr(self, k)

但结果是:
>>> asdict(Bla())
{'arg1': <__main__.none object at 0x7f71bc0159b0>, 'arg2': <__main__.none object at 0x7f71bc015a90>, 'arg3': <__main__.none object at 0x7f71bc015ac8>}

我期待一个空 dict
如果尝试:
>>> a = Bla(None, None, None)
>>> del a.__dict__["arg1"]
>>> asdict(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/(....)/venv/lib/python3.6/site-packages/dataclasses.py", line 1011, in asdict
return _asdict_inner(obj, dict_factory)
File "/home/(...)/venv/lib/python3.6/site-packages/dataclasses.py", line 1018, in _asdict_inner
value = _asdict_inner(getattr(obj, f.name), dict_factory)
AttributeError: 'Bla' object has no attribute 'arg1'

如何以我可以使用的方式从数据类对象中动态删除属性 asdict在那之后?

最佳答案

这不是您关于从数据类中删除属性的问题的答案,但它提供了一种获取自定义 asdict 的机制。它以您想要的方式运行:

from dataclasses import dataclass
from typing import Optional, Dict, cast

SENTINEL = cast(None, object()) # have a sentinel that pretends to be 'None'


@dataclass
class Bla:
arg1: Optional[int] = SENTINEL
arg2: Optional[str] = SENTINEL
arg3: Optional[Dict[str, str]] = SENTINEL

def asdict(self):
return {k: v for k, v in self.__dict__.items() if v is not SENTINEL}

一些测试:

>>> Bla().asdict()
{}
>>> Bla(None, None).asdict()
{'arg1': None, 'arg2': None}
>>> Bla(1, 'foo', None).asdict()
{'arg1': 1, 'arg2': 'foo', 'arg3': None}

但请记住,这都是谎言,当显式调用时,属性仍然存在:

>>> print(Bla().arg1)
<object object at 0x7fc89ed84250>

关于python - 如何删除数据类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58119758/

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