gpt4 book ai didi

Python 装饰器 : howto list wrapped functions by decorator

转载 作者:太空宇宙 更新时间:2023-11-04 10:09:37 25 4
gpt4 key购买 nike

如果我不知道包装函数的名称,是否可以使用 python 装饰器来标记一个方法,并获取它供以后使用?

这是例子,我不知道method_with_custom_name的名字:

@run_this_method
def method_with_custom_name(my_arg):
return "The args is: " + my_arg

def _init_and_run():
# Here, I want to get and call method_with_custom_name
# but I don't know it's name,
# so the next line isn't valid.
return run_this_method()(my_arg_value)

def run_this_method(m):
def w(my_arg):
_do_some_magic(my_arg, m)
return w

def _do_some_magic(callback_arg, callback):
if some_checks():
callback(callback_arg)

那么我怎样才能得到用@run_this_method包裹的方法列表

最佳答案

如果您需要跟踪所有用您的装饰器装饰的函数和方法,您需要创建全局变量来注册所有这些函数和方法。我修改了你的代码:

funcs_registry = [] #List of all functions decorated with @run_this_method
def run_this_method(m):
global functions_registry
funcs_registry.append(m) #Add function/method to the registry

def w(my_arg):
_do_some_magic(my_arg, m)
return w

def _do_some_magic(callback_arg, callback):
if some_checks():
callback(callback_arg)

@run_this_method
def method_with_custom_name(my_arg):
return "The args is: " + my_arg

def _init_and_run():
global functions_registry

# Here you can iterate over "functions_registry"
# and do something with each function/method in it
for m in functions_registry:
print(m.__name__)

除了使用全局变量 functions_registry 之外,您还可以创建类以用作装饰器并在实体字段中注册函数。像这样:

class FunDecorator:
def __init__(self):
self.registry = []

def __call__(self, m):
"This method is called when some method is decorated"
self.registry.append(m) #Add function/method to the registry

def w(my_arg):
_do_some_magic(my_arg, m)
return w

run_this_method = FunDecorator() #Create class instance to be used as decorator

@run_this_method
def method_with_custom_name(my_arg):
return "The args is: " + my_arg

#do some magic with each decorated method:
for m in run_this_method.registry:
print(m.__name__)

关于Python 装饰器 : howto list wrapped functions by decorator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39167171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com