基于类实现装饰器变体
在之前的文章里有提过基于类实现的装饰器,这里做一下延申
import types from functools import wraps class Decorator: def __init__(self, func): wraps(func)(self) self.calls = 0 def __call__(self, *args, **kwargs): self.calls += 1 print("preparing") return self.__wrapped__(*args, **kwargs) def __get__(self, instance, owner): """确保绑定方法对象的创建""" if instance is None: return self return types.MethodType(self, instance) class Valley: def __init__(self): ... @Decorator def get(self): print("running") Valley().get() print(Valley.get.calls)
如果不实现__get__方法,实例方法会缺少调用方对象的传递,大家可以自行尝试
output:
preparing
running
1
标签:__,多种,方式,get,self,instance,Valley,装饰,def From: https://www.cnblogs.com/shixiaogu/p/17402041.html