我如何使用装饰元数据执行Python函数,而无需调用原始功能。有可能吗? 我正在尝试的是我的Python代码。我期望存储的元数据列表。 内存装饰器的目的是“装饰”函数以存储元数据的代码。 导入功能 memory_s ...

问题描述 投票:0回答:1
我猜想您要存储功能并通过迭代列表迭代来调用它们。如果是这种情况,则将

memory_storage

调用在错误的函数中:当调用
append
/
python python-3.x
1个回答
0
投票
函数时,将附加内存,而不是应用装饰器时。尝试一下:

print_hello
输出:
import functools

memory_storage = []

def memory(func_names, description):
    def decorator(func):
        # This should be put here
        memory_storage.append({
            "func_names": func_names,
            "description": description,
            "function": func
        })
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        return wrapper
    return decorator

@memory(
    func_names=['print_weep'],
    description="This method will print the weep"
)
def print_weep():
    print("weep")

@memory(
    func_names=['print_hello'],
    description="This method will print hello"
)
def print_hello():
    print("hello")

def execute_functions():
    for entry in memory_storage:
        print(f"Executing function {entry['func_names'][0]}: {entry['description']}")
        entry['function']()  # Call the stored function

print("Stored Metadata:", memory_storage)
execute_functions()
	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.