如何理解Python装饰器?



                    
                    
今天天很蓝
67474 次浏览 2024-04-26 提问
32

最新回答 (1条回答)

2024-04-26 回答

def inject_check(method):
def my_method(*args):
print "before"
method(*args)
print "after"
return my_method
############################
#class Demo(object):
# def hello(self):
# print &q缉恭光枷叱磺癸委含莲uot;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)

相关问题

页面运行时间: 0.09252405166626 秒