python装饰器

来源:互联网 发布:nginx tengine 哪个好 编辑:程序博客网 时间:2024/04/20 17:01

请见   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 newdecclass A2:    def __init__(self):        pass    @mydecorator('Hello', 'word.')    def method(self, x, y):        print x, yif __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=21 2


原创粉丝点击