[英]passing/changing arguments of a function which is passed as an argument in another function
I have one weird problem. 我有一个奇怪的问题。 I want to pass/change an argument of a function which itself is passed as an argument in some other function. 我想传递/更改函数的参数,该函数本身作为其他函数中的参数传递。 See the below code for more details 请参阅下面的代码以获取更多详细信息
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 []
So I passed my post_processing
method along with all its parameters to my generic_method
by using functools's partial
and also passed a new variable attrval
to my post_processing method. 因此,我通过使用functools's partial
将了post_processing
方法及其所有参数传递给了generic_method
,并且还将一个新的变量attrval
传递给了我的post_processing方法。 But what is more desirable is to pass or assign attr_value
directly to variable y
to post_processing
. 但是,更理想的是将attr_value
直接传递或分配给变量y
或传递给post_processing
。
I was looking for ways to modify functions parameters during run-time. 我一直在寻找在运行时修改函数参数的方法。 I was searching over the net and found out that their is a inspect
library in python which tells you about the arguments passed to the function. 我在网上搜索,发现它们是python中的inspect
库,它告诉您传递给函数的参数。 Can it be used in this case. 在这种情况下可以使用吗?
In Python 3, you could do def post_processing(*args, y=None, **kwargs):
and that would be it. 在Python 3中,您可以执行def post_processing(*args, y=None, **kwargs):
就是这样。 With Python 2 you have to find a different technique than partial
. 使用Python 2,您必须找到与partial
不同的技术。 Or maybe subclass it as in implementing functools.partial that prepends additional arguments . 或者,可以在实现functools.partial时添加它的子类, 该函数附加了其他参数 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.