python装饰器

请见   http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html

多个参数的示例:

def mydecorator(arg1, arg2):
    print "level 1 : Arg1=%s, arg2=%s" % (arg1, arg2)
    def newdec(func):
        print 'level 2 : newdec was called. the arg is func=%s' % func
        def replace(self, x, y):
            print "level 3 : replace was called. self is %s, x=%s, y=%s" % (str(self), str(x), str(y))
            return func(self, x, y)
        return replace
    return newdec

class A2:
    def __init__(self):
        pass

    @mydecorator('Hello', 'word.')
    def method(self, x, y):
        print x, y

if __name__ == '__main__':
    a = A2()
    a.method(1, 2)

 

运行结果为:
level 1 : Arg1=Hello, arg2=word.
level 2 : newdec  was called. the arg is func=<function method at 0x04A06130>
level 3 :  replace was called. self is <__main__.A2 instance at 0x04A05850>, x=1,  y=2
1 2


你可能感兴趣的:(python装饰器)