如果在python中调用了函数列表中的任何函数,是否可以自动触发函数?
就像说函数a附加到函数列表[b,c,d,e]上,如果调用了[b,c,d,e]中的任何一个(例如说b()),则a()被自动调用之前吗?
我想在调用b之前使用函数a设置一些值,以便b可以使用它。
例如:
# function b is some inbuilt, library function
attach(a, b) #attach function b to function a
b()
# If function b is called first function a gets called, it changes up some
# global variables for the use of function b, then function b gets executed
我有一些全局变量和一些类方法,这些全局变量是诸如CLASSIFIER(例如LogisticRegression或XGBClassifier),CLASSIFIER_TYPE(例如'linear'或Tree)之类的,每次调用fit和预测其上的方法时都需要更改相应的管道(例如pipeline_linear或pipeline_tree).fit / predict。这是因为我编写了如下代码:
CLASSIFIER = LogisticRegression
CLASSIFIER_TYPE = 'linear'
pipeline_linear = make_pipeline(preprocessing_pipe, CLASSIFIER())
pipeline_linear.fit(X, y)
CLASSIFIER = XGBClassifier
CLASSIFIER_TYPE = 'tree'
pipeline_tree = make_pipeline(preprocessing_pipe, CLASSIFIER())
pipeline_tree.fit(X, y)
linear_preds = pipeline_linear.predict(X) # This statement throws an error
# because CLASSIFIER and CLASSIFIER_TYPE are not changed
# preprocessing_pipe uses CLASSIFIER_TYPE internally to take care of
# handling both types of classifiers differently.
因此,根据我使用的管线,需要对全局变量进行相应的修改,以使拟合和预测方法在管线(pipeline_linear和pipeline_tree)上起作用。
任何其他照顾这些情况的好方法都会很有帮助!
答案 0 :(得分:2)
使用包装纸。
如果您的函数是my_function
并且列表是list_of_functions
:
def func_wrapper(query):
for additional_function in list_of_functions:
# Do whatever you need to do with your list of functions
additional_function()
my_function(query)
答案 1 :(得分:1)
我认为您仍然可以使用装饰器/包装器之类的东西。看看这样的事情是否对您有用:
MY_GLOBAL = 123
def wrap_with_global_value(func, global_val):
def wrap(*args, **kwargs):
global MY_GLOBAL
prev_global_val = MY_GLOBAL
MY_GLOBAL = global_val
result = func(*args, **kwargs)
MY_GLOBAL = prev_global_val
return result
return wrap
class MyClass(object):
def my_func(self):
global MY_GLOBAL
print('from my_func: MY_GLOBAL is {}.'.format(MY_GLOBAL))
my_obj = MyClass()
my_obj.my_func = wrap_with_global_value(my_obj.my_func, 456)
print('Before calling my_func: MY_GLOBAL is {}.'.format(MY_GLOBAL))
my_obj.my_func()
print('After calling my_func: MY_GLOBAL is {}.'.format(MY_GLOBAL))
输出:
Before calling my_func: MY_GLOBAL is 123.
from my_func: MY_GLOBAL is 456.
After calling my_func: MY_GLOBAL is 123.
如果对您很重要,您可以添加functools.wraps
。
答案 2 :(得分:0)
当然,只需在每个其他函数的顶部调用该函数会更容易?
def setup():
# Set some variables
pass
def target1():
setup()
pass
def target2():
setup()
pass