[英]python dataclass asdict ignores attributes without type annotation
Python 文檔解釋了如何使用dataclass
asdict
但沒有說明沒有類型注釋的屬性會被忽略:
from dataclasses import dataclass, asdict
@dataclass
class C:
a : int
b : int = 3
c : str = "yes"
d = "nope"
c = C(5)
asdict(c)
# this returns
# {'a': 5, 'b': 3, 'c': 'yes'}
# note that d is ignored
如何在不自己實現函數的情況下使d
屬性出現在返回的字典中?
您可以使用Any
作為類型注釋。 例如:
from typing import Any
from dataclasses import dataclass, asdict
@dataclass
class C:
a : int
b : int = 3
c : str = "yes"
d : Any = "nope"
c = C(5)
asdict(c)
# this returns
# {'a': 5, 'b': 3, 'c': 'yes', 'd': 'nope'}
# Now, d is included as well!
一種俗氣且有點不專業的方法是用任何隨機字符串值對其進行注釋。
因此,例如:
from dataclasses import dataclass, asdict
@dataclass
class C:
a : int
b : int = 3
c : str = "yes"
d: 'help,, i dunno how [a]ny of this w@rks!!' = "nope"
c = C(5)
print(asdict(c))
# this returns
# {'a': 5, 'b': 3, 'c': 'yes', 'd': 'nope'}
經過一番思考,這實際上可以簡化為:
@dataclass
class C:
a : int
b : int = 3
c : str = "yes"
d: ... = "nope"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.