gpt4 book ai didi

python - 如何创建一个具有大量属性而不重复代码的类?

转载 作者:行者123 更新时间:2023-12-01 09:01:23 26 4
gpt4 key购买 nike

我有以下类来表示新闻提醒

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新手,想知道有什么方法可以更清晰地组织它吗?也许与数据类一起。

最佳答案

你可以做类似的事情

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)

但是,我会重新思考整个类(class)结构。类不仅仅是字典,属性也应该在某个地方使用。如果不是,它们只是一个数据结构。如果是,您可能应该将这些参数的子集分组到其他类中。

关于python - 如何创建一个具有大量属性而不重复代码的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52430537/

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