【问题标题】:update object with function call使用函数调用更新对象
【发布时间】:2018-03-04 22:00:07
【问题描述】:

我正在使用第 3 方包,它从源对象上的昂贵方法调用定义结果对象:result_object = source_object.method(input_value)

我想在函数调用中修改result_object,如下所示:

def modify_result(result_object, update_value):
    result_object = source_object.method(update_value)

显然发布的代码不起作用;它只是创建一个被丢弃的本地result_object。相反,我可以:

  • 在函数中将result_object设为nonlocal,如上修改
  • 扩展result_object 类并添加modify_result 方法
  • 还有别的吗?

一些澄清。在这种情况下,result_object 是否被认为是全球性的?更重要的是,是否有首选方法来更新result_object,以便其他功能可以访问它?

【问题讨论】:

  • 你为什么不直接返回result_object
  • 在您的问题中提供Minimal, Complete, Verifiable Example
  • @Alex 返回result_object 必然调用昂贵的方法。我想访问修改后的结果,而不是每次都调用它
  • @ConfusinglyCuriousTheThird 什么是便宜的方法?
  • 您可以将global result_object 放在函数的开头,但有时会不受欢迎

标签: python methods scope functional-programming


【解决方案1】:

在您的示例中,贵与廉价操作之间的区别不是很清楚 - 您只是在展示昂贵的操作吗?

无论如何,听起来您有一项昂贵的操作和一项便宜的操作,并且您希望能够在适用的情况下使用便宜的操作。要做到这一点,我认为你需要一个现有的对象来利用,所以我建议有一个可选的关键字参数来提供这样一个对象,但无论是否提供返回值,都使返回值成为相同的结果类型。比如:

def process_data(new_data, existing_result=None):
    if existing_result is None:
        # create a new result object
        return make_result_via_expensive_op(new_data)
    else:
        # modify an existing result object
        existing_result.modify_via_cheap_op(new_data)
        return existing_result

我不建议将其设为全球性。您可以更轻松地传递引用,并且更容易遵循代码。

【讨论】:

    猜你喜欢
    • 2015-09-11
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 2011-02-04
    相关资源
    最近更新 更多