Python 装饰器参数

0 投票
1 回答
2047 浏览
提问于 2025-04-17 17:40

Python 的装饰器函数支持参数吗?它是怎么实现的呢?

def decorator(fn, decorArg):
    print "I'm decorating!"
    print decorArg
    return fn

class MyClass(object):
    def __init__(self):
        self.list = []

    @decorator
    def my_function(self, funcArg = None):
        print "Hi"
        print funcArg

运行时我遇到了这个错误

TypeError: decorator() takes exactly 2 arguments (1 given)

我试过 @decorator(arg) 或者 @ decorator arg,但都不行。目前我在想这是否可能实现。

1 个回答

3

我觉得你可能想要这样的东西:

class decorator:
    def __init__ (self, decorArg):
        self.arg = decorArg

    def __call__ (self, fn):
        print "I'm decoratin!"
        print self.arg
        return fn

class MyClass (object):
    def __init__ (self):
        self.list = []

    @decorator ("foo")
    def my_function (self, funcArg = None):
        print "Hi"
        print funcArg

MyClass ().my_function ("bar")

或者像BlackNight提到的那样使用嵌套函数:

def decorator (decorArg):
    def f (fn):
        print "I'm decoratin!"
        print decorArg
        return fn
    return f

撰写回答