由decoree访问装饰者的名字

时间:2018-03-06 19:18:43

标签: python decorator python-decorators

我正在使用_ foo

装饰一个函数decorator
@a_decorator(params)
def foo(x):
#    print('Called',decorator_name)
#    other magic

有没有办法访问a_decorator内的名称foo,以便我可以打印

  

'称为a_decorator'

def a_decorator(some_function):
    def wrapper():
        some_function()
        return some_val
    return wrapper

1 个答案:

答案 0 :(得分:1)

可以通过将装饰者名称附加到包装函数来完成:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript">
        var click = 0;
        function clicked(){
            var num = Math.floor((Math.random() * 100) + 1);

            click = click+1;
            if(num == 1){
                document.getElementById("print").innerHTML="Congratz! You did it in "+click+" times!";
                document.getElementById("press").disabled = true;
            }
            else{
                document.getElementById("print").innerHTML="Not the right number! You 've pressed "+click+" times!";
            }
        }
    </script>
</head>
<h1>TEST YOUR LUCK!</h1>
<body>
    <input type="button" value="Press Me!" id="press" onclick="clicked()">
    <div id="print"></div>
</body>
</html>

python中的函数是第一类,您可以将它们视为对象,附加属性等。