python decorator不起作用

时间:2015-11-17 05:19:12

标签: python decorator

我是python的新手。我想将参数传递给类derorator:

class TestClass(object):
    def __init__(self, name):
        super(TestClass, self).__init__()
        self.name = name

    def age(self, func, age=0):
        def wrapper(*args, **kwargs):
            if age >= 18:
                print "you are not a child"
            else:
                print "you are a child"
            func()
        return wrapper

test = TestClass("liu")

@test.age(age=12)
def hello():
    print "hello, world!"

但错误如下:

Traceback (most recent call last):
  File "/Users/liux/Desktop/test.py", line 17, in <module>
    @test.age(age=12)
TypeError: age() takes at least 2 arguments (2 given)

对此有任何想法。

1 个答案:

答案 0 :(得分:5)

age应该是一个返回装饰器的方法。 (不是装饰者)

所以看起来应该是这样的:

def age(self, age=0):
    def deco(func):
        def wrapper(*args, **kwargs):
            if age >= 18:
                print "you are not a child"
            else:
                print "you are a child"
            func()  # OR  return func(*args, **kwargs)
        return wrapper
    return deco