gpt4 book ai didi

python - 方法 __init__ 参数过多

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

我对 Python 非常陌生(大约 3 周前开始),我正在尝试制作一个脚本来抓取网页以获取信息。检索到信息后,它会通过一个函数对其进行格式化,然后将其传递给一个采用 17 个变量作为参数的类。该类使用此信息来计算其他一些变量,并且当前有一个构造字典的方法。代码按预期工作,但我在 Pycharm 中使用的一个名为 SonarLint 的插件突出显示 17 个变量太多而无法用作参数?

我一直在寻找将信息传递给类的替代方法,例如在元组或列表中,但找不到太多似乎相关的信息。将许多变量作为参数传递给类的最佳实践是什么?或者我根本不应该使用类来做这种事情?

为了便于阅读,我减少了变量和代码的数量,但这是类;

Class GenericEvent:

def __init__(self, type, date_scraped, date_of_event, time, link,
blurb):

countdown_delta = date_of_event - date_scraped
countdown = countdown_delta.days

if countdown < 0:
has_passed = True
else:
has_passed = False

self.type = type
self.date_scraped = date_scraped
self.date_of_event = date_of_event
self.time = time
self.link = link
self.countdown = countdown
self.has_passed = has_passed
self.blurb = blurb

def get_dictionary(self):

event_dict = {}
event_dict['type'] = self.type
event_dict['scraped'] = self.date_scraped
event_dict['date'] = self.date_of_event
event_dict['time'] = self.time
event_dict['url'] = self.link
event_dict['countdown'] = self.countdown
event_dict['blurb'] = self.blurb
event_dict['has_passed'] = self.has_passed

return event_dict

在通过以下方式清理数据后,我一直将变量作为键:值对传递给类:

event_info = GenericEvent(type="Lunar"
date_scraped=30/01/19
date_of_event=28/07/19
time=12:00
link="www.someurl.com"
blurb="Some string.")

并通过调用检索字典:

event_info.get_dictionary()

我打算向该类添加其他方法,以便也能够执行其他操作(不仅仅是创建 1 个字典),但希望在扩展该类的功能之前解决这个问题。

任何帮助或链接将不胜感激!

最佳答案

一个选项是命名元组:

from typing import Any, NamedTuple


class GenericEvent(NamedTuple):
type: Any
date_scraped: Any
date_of_event: Any
time: Any
link: str
countdown: Any
blurb: str

@property
def countdown(self):
countdown_delta = date_of_event - date_scraped
return countdown_delta.days

@property
def has_passed(self):
return self.countdown < 0

def get_dictionary(self):
return {
**self._asdict(),
'countdown': self.countdown,
'has_passed': self.has_passed,
}

(将Any替换为字段的实际类型,例如datetime.datetime。)

或者,如果您希望它是可变的,则 data class .

关于python - 方法 __init__ 参数过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55447102/

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