注册单个函数
importrequestsclassreq(object): def__init__(self): self.funs=Nonedefget(self, url): ifself.funs: self.funs() resp=requests.get(url=url) returnrespdefpost(self, url): resp=requests.post(url=url) returnrespdefreg_funs(self, funs): self.funs=funsdemo=req() defhello(): print("hello,word") #注册函数demo.reg_funs(hello) resp=demo.get(url="https://www.baidu.com") print(resp.status_code) #注册函数reg_funs .defgood(): print("hello,goold") resp=demo.get(url="https://www.baidu.com") print(resp.status_code)
运行结果,自动执行了额外的函数good
hello,word 200 hello,goold 200
注册多个函数
importrequestsclassreq(object): def__init__(self): self.funs= [] defget(self, url): forfinself.funs: f() resp=requests.get(url=url) returnrespdefpost(self, url): resp=requests.post(url=url) returnrespdefreg_funs(self, funs): self.funs.append(funs) demo=req() defhello(): print("funcs1111") # 注册函数reg_funs .defgood(): print("funcs2222") #注册函数demo.reg_funs(hello) resp=demo.get(url="https://www.baidu.com") print(resp.status_code)
运行结果,注册的2个函数都额外执行了
funcs2222 funcs1111 200