标签:span 替换 临时对象 fun 顺序 cal 需要 name python
+----------------------------+----------------------------+ | @decorator | def func(): | | def func(): | .... | | .... | func = decorator(func) | +----------------------------+----------------------------+ | func() | decorator(func)() | +----------------------------+----------------------------+
def decorator(F): def tmp_F(*args_for_F): 这个函数内可以添加任你想执行的代码。 F(*args_for_F) return tmp_F # 这个返回的是函数地址
class decorator: def __init__(self, F): self.__func = F def __call__(self, *args_for_F): self.__func(*args_for_F) * 注意:这个方式,被装饰对象如果是类中的函数,则不能正常工作,self的含义发生了变化。
+----------------------------+----------------------------+ | @decorator | class C: | | class C: | .... | | .... | C = decorator(C) | +----------------------------+----------------------------+ | C() | decorator(C)() | +----------------------------+----------------------------+
def decorator(cls): class tmp_C: def __init__(self, *args): # cls(*args) --> 走的是被装饰类的创建对象流程,然后把返回的对象 # 存放在装饰器类实例对象的一个静态属性中。 self.__instance = cls(*args) # 最终访问的是装饰器类返回的实例,这个实例的属性与被装饰类实例的属性是 # 一样的。实现方法就是:属性的传递。 def __getattr__(self, name): return getattr(self.__instance, name) return tmp_C @decorator class Person def __init__(self, name, sex): self.name = name self.sex = sex # 末尾自动加上代码:Person = decorator(Person) x = Person(‘Tim‘, ‘Male‘) # x = Person(‘Tim‘, ‘Male‘) ---> Person已经
# 相当于tmp_C了,调用的是tmp_C.__init__ print(x.name) # 调用的是 getattr(Person对象, name), 返回的是:‘Tim‘
各种实现都存在缺点,推荐使用函数方式。类方式主要特点是考虑,__init__ 会被decorator()调用,对象调用,obj(),会调用decorator.__call__方法。
+-------------------------+-------------------------+ | @A | | | @B | | | @C | fc = C(my_func) | | def my_func(..): | fb = B(fc) | | ... | fa = A(fb) | +-------------------------+-------------------------+ | @A | | | @B | | | @C | cc = C(MyClass) | | class MyClass: | bc = B(cc) | | ... | ac = A(bc) | +-------------------------+-------------------------+
+----------------------------+----------------------------+ | @decorator(A,B) | def func(): | | def func(): | .... | | .... | f1 = decorator(A,B) | | | func = f1(func) | +----------------------------+----------------------------+ | func() | decorator(A,B)(func)() | +----------------------------+----------------------------+ def decorator(A,B): def f1(func): def f2(*args_for_func): ... return f2 return f1
标签:span 替换 临时对象 fun 顺序 cal 需要 name python
原文地址:https://www.cnblogs.com/timlinux/p/9193002.html