我有以下用于表示新闻提醒的课程
class Incident:
news_id: Optional[str] = None
created_at: str
service: str
status: str
title: str
content: str
category: Optional[str] = None
news_url: Optional[str] = None
updated_at: Optional[str] = None
published_at: Optional[str] = None
city: Optional[str] = None
state: Optional[str] = None
....
def __init__(self,
status: str, service: str, created_at: str, title: str, content: str, news_id: Optional[str] = None,
category: Optional[str] = None, news_url: Optional[str] = None, updated_at: Optional[str] = None,
published_at: Optional[str] = None, city: Optional[str] = None, state: Optional[str] = None,
country: Optional[str] = None, address: Optional[str] = None, region: Optional[str] = None,
latitude: Optional[float] = None, longitude: Optional[float] = None,
images: Optional[List[Dict[str, str]]] = None):
self.news_id = news_id
self.status = status
self.category = category
self.service = service
self.title = title
self.content = content
self.news_url = news_url
self.created_at = created_at
self.updated_at = updated_at
self.published_at = published_at
self.city = city
self.state = state
self.country = country
self.address = address
self.region = region
self.latitude = latitude
self.longitude = longitude
self.images = images
我认为整个班级看起来都很丑。属性被列出三遍。
我是python的新手,想知道有什么方法可以更清晰地组织它吗?也许有数据类。
答案 0 :(得分:1)
您可以做类似的事情
class Test:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
test = Test(a=1, b=2)
print(test.a)
print(test.b)
但是,我会重新考虑整个类的结构。类不仅是字典,属性还应在某个地方使用。如果不是,则它们只是数据结构。如果是这样,您可能应该将这些参数的子集分组到其他类中。