方法初始化“”的参数太多

2024-07-07 00:44:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的超级新手(我大约3周前就开始了),我正在尝试制作一个脚本来获取web页面上的信息。在检索到信息后,它通过一个函数对其进行格式化,然后将其传递给一个类,该类接受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

我把变量作为键:值对在我清理完数据后,按以下方式发送给类:

^{pr2}$

通过调用以下命令检索字典:

event_info.get_dictionary()

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

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


Tags: ofselfevent信息date字典timetype
2条回答

一个选项是命名元组:

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。在

我不认为你的所作所为有什么问题。但是,您可以将参数作为单个dict对象,然后通过迭代dict或对每个dict执行显式操作来处理它们。对你来说,这似乎会让你的代码更混乱。在

由于构造函数中的所有参数都是命名参数,因此可以执行以下操作:

def __init__(self, **params):

这将给您一个名为params的dict,然后您可以处理它。键是参数名,值是参数值。在

如果将参数名与get_dictionary方法的返回值中的键对齐,则将该参数作为一个整体保存可能会使该方法的编写变得非常简单。在

下面是您的代码的缩写版本(修复了一些语法错误),说明了这一点:

^{pr2}$

结果:

{'blurb': 'Some string.',
 'date_of_event': '28/07/19',
 'date_scraped': '30/01/19',
 'link': 'www.someurl.com',
 'time': '12:00',
 'type': 'Lunar'}

相关问题 更多 >