Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 检查Python函数是否用特定的修饰符修饰_Python 2.7_Python Decorators - Fatal编程技术网

Python 2.7 检查Python函数是否用特定的修饰符修饰

Python 2.7 检查Python函数是否用特定的修饰符修饰,python-2.7,python-decorators,Python 2.7,Python Decorators,我想检查Python函数是否被修饰,并将修饰器参数存储在函数dict中。这是我的代码: from functools import wraps def applies_to(segment="all"): def applies(func): @wraps(func) def wrapper(*args, **kwargs): func.func_dict["segment"] = segment prin

我想检查Python函数是否被修饰,并将修饰器参数存储在函数dict中。这是我的代码:

from functools import wraps

def applies_to(segment="all"):
    def applies(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            func.func_dict["segment"] = segment
            print func.__name__
            print func.func_dict
            return func(*args, **kwargs)
        return wrapper
    return applies
但看起来这条格言丢了:

@applies_to(segment="mysegment")
def foo():
    print "Some function"


> foo() # --> Ok, I get the expected result
foo
{'segment': 'mysegment'}

> foo.__dict__ # --> Here I get empty result. Why is the dict empty?
{}
好的,多亏了他的线索,我找到了答案。即使有所改善

from functools import wraps

def applies_to(*segments):
    def applies(func):
        func.func_dict["segments"] = list(segments)
        @wraps(func)
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        return wrapper
    return applies

谢谢

您在错误的时间修改了错误的函数。我是否应该在运行时修改“应用”函数?