首页 > 装修问答 > 装饰 > 如何理解Python装饰器?

如何理解Python装饰器?

浏览次数:313|时间:2024-05-14

热门回答

2024-05-06雅婷0302
def inject_check(method): def my_method(*args): print "before" method(*args) print "after" return my_method############################ #class Demo(object):# def hello(self):# pri迹绩管啃攮救归寻害默nt "hello"# hello=inject_check(hello)########################## class Demo(object): @inject_check def hello(self): print "hello" d = Demo()d.hello()就是在函数上加个包装,如上面代码中的hello函数加上@inject_check装饰器,等价于将函数hello重新赋值:hello=inject_check(hello)

92