【问题标题】:passing/changing arguments of a function which is passed as an argument in another function传递/更改作为另一个函数中的参数传递的函数的参数
【发布时间】:2015-12-04 01:43:04
【问题描述】:

我有一个奇怪的问题。我想传递/更改一个函数的参数,该函数本身作为参数传递给其他函数。详情见以下代码

def generic_method(selector_type='CSS', selector=None, parent_element=None, postfunc=None):

    # Do your stuff and get value of attr_value
    print "Doing Stuff"
    attr_value = '$123.70'

    print "Post-Processing Step"
    if postfunc:
        attr_value = postfunc(attrval=attr_value)

    return attr_value

# The 2 methods below are in separate file 
from functools import partial
def method_in_bot():
    p, q, r = 11, 12, 13
    postfunc = partial(post_processing, 12, p, q, r, post=23)
    value = generic_method('XPATH', '.class-name', 'parent_element', postfunc)
    return value

def post_processing(y=None, *args, **kwargs):
    attr_value = kwargs.get('attrval', 'None')
    if attr_value:
        return attr_value.split('$')
    return []

所以我通过使用functools's partial 将我的post_processing 方法及其所有参数传递给我的generic_method,并将一个新变量attrval 传递给我的post_processing 方法。但更可取的是将attr_value直接传递或赋值给变量ypost_processing

我一直在寻找在运行时修改函数参数的方法。我在网上搜索,发现它们是 python 中的inspect 库,它告诉你传递给函数的参数。这种情况下可以用吗?

【问题讨论】:

  • > 但更可取的是将 attr_value 直接传递或分配给变量 y 到 post_processing。
  • 是的,而不是 postfunc(attrval=attr_value) 我想调用 attr_value = postfunc(y=attr_value)。
  • 可以postfunc args 的元组和/或字典传递给generic_method。但是你现在做的很好,恕我直言。虽然使用inspect 进行深度魔法可能会使您的代码的某些部分更易于编写,但它也会使您的程序更难阅读。易于阅读通常应优先于易于书写。

标签: python inspect functools


【解决方案1】:

在 Python 3 中,您可以使用def post_processing(*args, y=None, **kwargs):,就是这样。使用 Python 2,您必须找到与 partial 不同的技术。或者可能将其子类化为 implementing functools.partial that prepends additional arguments

【讨论】:

    最近更新 更多