美文网首页
Python装饰器17-将装饰器类应用于类的成员函数

Python装饰器17-将装饰器类应用于类的成员函数

作者: dnsir | 来源:发表于2019-06-16 00:35 被阅读0次

有没有可能将装饰器类应用于类的成员函数呢?根据之前的分析,似乎是可以的,代码:


from functools import wraps

class Profiled:

    def __init__(self, func):
        wraps(func)(self)

    def __call__(self, *args, **kwargs):
        print("call")
        return self.__wrapped__(*args, **kwargs)
    
class Spam:

    @Profiled
    def bar(self, x):
        print(self, x)

s = Spam()
s.bar(1)

执行结果:

call
Traceback (most recent call last):
  File "decorator146.py", line 21, in <module>
    s.bar(1)
  File "decorator146.py", line 12, in __call__
    return self.__wrapped__(*args, **kwargs)
TypeError: bar() missing 1 required positional argument: 'x'

似乎出现了问题。

当装饰器类应用于类成员函数时,类成员函数变成什么样了?


from functools import wraps

class Profiled:

    def __init__(self, func):
        wraps(func)(self)

    def __call__(self, *args, **kwargs):
        print("call")
        return self.__wrapped__(*args, **kwargs)
    
class Spam:

    @Profiled
    def bar(self, x):
        print(self, x)

s = Spam()
print(s)
print(s.bar)
print(s.__dict__)
print(Spam.__dict__)

运行结果:

<__main__.Spam object at 0x7f363ceae550>
<__main__.Profiled object at 0x7f363d10d6a0>
{}
{'__module__': '__main__', 'bar': <__main__.Profiled object at 
0x7fd313c686a0>, '__dict__': <attribute '__dict__' of 'Spam' objects>, 
'__weakref__': <attribute '__weakref__' of 'Spam' objects>, '__doc__': 
None}

发现此时bar的属性竟然变为一个类的属性!
非常类似通过以下代码定义的Spam

class Spam:
    bar = Profiled()

此时我们继续理解之前将类作为装饰器应用于成员函数时。

s.bar(1)

调用分为2个步骤:

  1. s.bar 获取bar的类实例
  2. s.bar(1),对类实例进行调用

第一条需要根据之前所描述,需要实现__get__函数
第二条需要实现__call__属性
备注:其实包含3步,还有一步是__init__

正确的方法

import types
from functools import wraps

class Profiled:

    def __init__(self, func):
        wraps(func)(self)

    def __call__(self, *args, **kwargs):
        print("call")
        return self.__wrapped__(*args, **kwargs)

    def __get__(self, instance, cls):
        if instance is None:
            print('1')
            print(self)
            return self
        else:
            print('2')
            print(types.MethodType(self, instance))
            return types.MethodType(self, instance)
    
class Spam:

    @Profiled
    def bar(self, x):
        print(self,x)

s = Spam()
# print(s)
# print(s.bar)
# print(s.__dict__)
# print(Spam.__dict__)
s.bar(1)

运行结果:

2
<bound method Spam.bar of <__main__.Spam object at 0x7fc08562c5c0>>
call
<__main__.Spam object at 0x7fc08562c5c0> 1

结果是预期的,
至于__get__函数的三个参数的意义详解可以参考Python官网文档,这里只是大概说明
instance表示所在的,上述代码就是Spamcls参数指的就是Profiled
至于types.MethodType表示的意义就是什么就查看官网文档就行。

当然这里还有一些问题似乎无法理解,继续看看types.MethodType等就可以理解。这里不再累述了。

小结

将装饰器类应用于类的成员函数其实是最复杂的场景,当然装饰器应用的场景远不止提到的这几种,在<Python学习手册>里就介绍了很多种,可以看看教材中其余装饰器的使用,不过基本原理就是连载里所提到的。

相关文章

  • Python装饰器17-将装饰器类应用于类的成员函数

    有没有可能将装饰器类应用于类的成员函数呢?根据之前的分析,似乎是可以的,代码: 执行结果: 似乎出现了问题。 当装...

  • 装饰器函数

    在Python有一类特殊的函数,叫装饰器函数。装饰器函数可以在函数的调用的时候,将装饰器的内容注入到函数之中。在定...

  • 解惑,从新认识python装饰器

    概念 python有两种装饰器: 函数装饰器(function decorators) 类装饰器(class de...

  • Python装饰器

    Python装饰器 一、函数装饰器 1.无参装饰器 示例:日志记录装饰器 2.带参装饰器 示例: 二、类装饰器 示例:

  • 装饰器

    装饰器 decorator类装饰器 带参数的装饰器 举例(装饰器函数;装饰器类;有参与无参) https://fo...

  • Python装饰器

    Python装饰器 装饰器作用 装饰器可也用来扩展函数或者类的功能,在不改变原有主体函数或类的情况下,简便的为其扩...

  • decorator

    装饰器 装饰类对象@testclass A{}function test(target){//类对象装饰器函数ta...

  • 装饰器4

    装饰器装饰类 使用类装饰器的时候,记得要返回被装饰的类调用的结果装饰器函数 再 init 之前执行 例子1:给类添...

  • TypeScript——装饰器(四)

    参数装饰器 参数装饰器声明在一个参数声明之前(紧靠着参数声明)。 参数装饰器应用于类构造函数或方法声明。 参数装饰...

  • python 装饰器(类装饰器和函数装饰器)

    一、函数装饰器示例 二、类装饰器

网友评论

      本文标题:Python装饰器17-将装饰器类应用于类的成员函数

      本文链接:https://www.haomeiwen.com/subject/pefwfctx.html