如果在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)。你知道吗
任何其他处理这些情况的好方法都会非常有用!你知道吗
我想你还是可以用装饰器/包装器之类的东西。看看这样的东西是否适合你:
输出:
如果这对您很重要,您可以添加^{} 。你知道吗
当然,只调用彼此函数顶部的函数会更容易吗?你知道吗
用包装纸。你知道吗
如果函数是
my_function
,列表是list_of_functions
:相关问题 更多 >
编程相关推荐