如何解决python:将实例方法及其参数传递给函数以执行
我知道如何将函数作为参数传递,然后再使用该函数。但是我不知道如何用一种方法来做到这一点。我想为用户提供一个“ API”,使他们可以配置自定义功能。
作为一个(不是)工作示例,假设我希望用户能够提供一些常规的熊猫功能:
import pandas as pd
# user-supplied data
right = pd.DataFrame({'right_a':[1,2],'right_b':[3,4]})
# user-supplied function & arguments
myfun = pd.DataFrame.merge
args = {'right':right,'right_on':'right_a','how':'inner'
}
user_configs = {'func': myfun,'args':args}
def exec_func(exec_dict):
# some data that only the function knows:
left = pd.DataFrame({'left_a':[1,'left_b':['foo','bar']})
# some args that only the function knows
exec_dict['args']['left_on'] = 'left_a'
# apply the function
#result = left.merge(**exec_dict['args']) # desired result
result = left.exec_dict['func'](**exec_dict['args']) # generalized but not working code
return result
exec_func(user_configs)
上面的代码导致
AttributeError: 'DataFrame' object has no attribute 'exec_dict'
出于明显的原因。我该如何实现所需的行为,从而允许用户提供不同的功能?
解决方法
所以我稍微简化了您的问题,并省略了熊猫。通过名称调用实例方法的方法是通过 getattribute 方法:
class MethodProvider (object):
def __init__(self):
pass
def method1(self,foo):
print('Method1 was called with arguments %s'%foo)
def method2(self,baz):
print('Method2 was called with argument %s'%baz)
def exec_method(obj,meth,kwargs):
func = obj.__getattribute__(meth)
func(**kwargs)
# Test construction
mp = MethodProvider()
exec_method(
mp,'method1',{'foo': 'bar'}
)
exec_method(
mp,'method2',{'baz': 'buzz'}
)
,
从广义上讲,方法是函数,它们将实例作为第一个参数。 exec_dict['func']
已经是该方法,不需要在left
上查找它。只需将left
作为第一个参数即可。
# |method/function|| called with... |
result = exec_dict['func'](left,**exec_dict['args'])
# | instance
# | further arguments
此代码适用于将数据框left
作为其第一个参数的所有可调用对象,而不仅仅是数据框方法。
func
可以直接接收它们,而不是期望args
和exec_func
包裹在字典中。 left_on
也可以直接传递。
def exec_func(func,**args):
left = pd.DataFrame({'left_a':[1,2],'left_b':['foo','bar']})
# apply the function
result = func(left,left_on='left_a',**args)
return result
exec_func(**user_configs)
请注意,习惯上使用args
for positional and kwargs
for keyword arguments/parameters,即def exec_func(func,*args,**kwargs): ...
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。