我有以下数据类:
@dataclass
class Image:
content_type: str
data: bytes = b''
id: str = ""
upload_date: datetime = None
size: int = 0
def to_dict(self) -> Dict[str, Any]:
result = {}
if self.id:
result['id'] = self.id
if self.content_type:
result['content_type'] = self.content_type
if self.size:
result['size'] = self.size
if self.upload_date:
result['upload_date'] = self.upload_date.isoformat()
return result
有什么办法可以简化to_dict
方法吗?我不想使用 if
列出所有字段。
最佳答案
根据 meowgoesthedog 的建议, 你可以使用 asdict
并过滤结果以跳过虚假值:
from dataclasses import dataclass, asdict
from datetime import datetime
from typing import Dict, Any
@dataclass
class Image:
content_type: str
data: bytes = b''
id: str = ""
upload_date: datetime = None
size: int = 0
def to_dict(self) -> Dict[str, Any]:
return {k: v for k, v in asdict(self).items() if v}
print(Image('a', b'b', 'c', None, 0).to_dict())
# {'content_type': 'a', 'data': b'b', 'id': 'c'}
关于python - 如何从没有 None 字段的类创建字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57305749/