【问题标题】:Put repetitive code inside of function or custom class?将重复代码放在函数或自定义类中?
【发布时间】:2021-07-10 20:14:39
【问题描述】:

我知道自定义类在 OOP 和 Python 中非常方便。您可以拥有具有预定义属性的对象。

我在 Python 中有几个函数,在函数定义的开头有重复的代码。

它应该是一些 DRY 解决方案,可能基于为此功能创建一个类,但我的谷歌搜索没有产生任何结果。

在 Python 中是如何完成的?

UPD。这是一个例子。

def my_function1():
    options = Options()
    options.add_argument('--someargument')
    driver = webdriver.Chrome(options=options)

在 my_function2、my_function3 等中有三行必须重复。

UPD 2.

起跑线很容易用一个函数解决(见 MattDMo 的答案)。但是我怎样才能在 my_function(s) 中使用结尾行来干燥(不要重复自己):

    cookies = driver.get_cookies()
    pickle.dump(cookies, open('cookies.pkl', 'wb'))

    driver.close()

我找到的解决方案是这样的。首先用所需的代码块(如宏)定义一个变量:

chunk_of_code = '''
cookies = driver.get_cookies()
pickle.dump(cookies, open('cookies.pkl', 'wb'))
driver.close()
'''

并插入到 my_function 的末尾:

    exec(chunk_of_code)
    return something

它又快又脏,但它暂时适用于我的简单程序。 我错过了什么吗?

【问题讨论】:

  • 为什么不把重复的代码放在一个单独的函数中,在其他函数定义中直接调用该函数?
  • 我同意,听起来你只需要一个函数。
  • OOP 用于打包大量对一组通用数据进行操作的函数。如果只是重复代码,使用普通函数。
  • 你也可以使用装饰器(realpython.com/primer-on-python-decorators):可以“包装”另一个函数的特殊函数。 Python 中的元编程类型
  • @MattDMo 请检查我在已编辑问题中的示例。看起来我不能只定义一个带有重复代码的函数并在我的目标函数中调用它。至少,当我在问问题之前尝试过时它没有用。

标签: python function class dry


【解决方案1】:

您不是 returning my_function1() 的结果,因此它可以被其他函数使用。试试这个:

def setup_webdriver(arg="--generic_argument"):
    options = Options()
    options.add_argument(arg)
    driver = webdriver.Chrome(options=options)
    return driver # this is the important part

def first_real_function(arg1, arg2, arg3, ...):
    arg = "--real_argument_one"
    driver = setup_webdriver(arg)
    # continue other work with driver using --real_argument_one

def second_real_function(arg1, arg2, arg3, ...):
    arg = "--real_argument_two"
    driver = setup_webdriver(arg)
    # continue other work with driver using --real_argument_two

【讨论】:

  • 最终,这是我最终的结果。但是你能检查我的更新 2 吗?
猜你喜欢
  • 2017-06-29
  • 2022-11-08
  • 1970-01-01
  • 1970-01-01
  • 2014-06-26
  • 1970-01-01
  • 2017-11-25
  • 1970-01-01
  • 2014-02-15
相关资源
最近更新 更多