如果在Python中调用函数列表中的任何函数,则自动触发函数

2024-04-19 22:11:46 发布

您现在位置:Python中文网/ 问答频道 /正文

如果在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 

我有一些全局变量和一些类方法,全局变量是像分类器(例如LogisticRegression或XGBClassifier),分类器类型(例如“linear”或Tree),我每次调用fit和predict方法时都需要更改它们各自的管道(例如pipeline\u linear或pipeline\u 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\u linear和pipeline\u tree)。你知道吗

任何其他处理这些情况的好方法都会非常有用!你知道吗


Tags: of方法函数tree管道pipelinetypefunction
3条回答

我想你还是可以用装饰器/包装器之类的东西。看看这样的东西是否适合你:

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.

如果这对您很重要,您可以添加^{}。你知道吗

当然,只调用彼此函数顶部的函数会更容易吗?你知道吗

def setup():
    # Set some variables
    pass

def target1():
    setup()
    pass

def target2():
    setup()
    pass

用包装纸。你知道吗

如果函数是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)

相关问题 更多 >