【发布时间】: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直接传递或赋值给变量y到post_processing。
我一直在寻找在运行时修改函数参数的方法。我在网上搜索,发现它们是 python 中的inspect 库,它告诉你传递给函数的参数。这种情况下可以用吗?
【问题讨论】:
-
> 但更可取的是将 attr_value 直接传递或分配给变量 y 到 post_processing。
-
是的,而不是 postfunc(attrval=attr_value) 我想调用 attr_value = postfunc(y=attr_value)。
-
您可以将
postfuncargs 的元组和/或字典传递给generic_method。但是你现在做的很好,恕我直言。虽然使用inspect进行深度魔法可能会使您的代码的某些部分更易于编写,但它也会使您的程序更难阅读。易于阅读通常应优先于易于书写。