美文网首页
Python装饰器类的使用——bound/unbound met

Python装饰器类的使用——bound/unbound met

作者: CodingGuy | 来源:发表于2018-09-25 08:11 被阅读0次

    引言

    在学习装饰器类方法时发现,如果装饰器类只有__ call __方法则只能装饰普通的函数(function),不能对实例方法(instance method)进行装饰,经过研究发现与python的函数实现有关。本文就此展开讨论,并给出一个完整的装饰器类实现方法。

    问题发现

    我们都知道,当我们调用一个类的实例方法时,实例会作为方法的第一个入参self。而在下面的例子中,实例方法foo被装饰器类Decorator装饰后,Decorated().foo('hello, world')的第一个入参self并不是Decorated实例,而是我们传进去的"hello, world",很明显这是不符合我们预期的。实际上这与python的函数调用有关,bound method(通过实例调用的方法)会自动将实例本身作为方法的第一个入参,而function和unbound method(类直接调用的方法)不会自动注入实例。当我们用装饰器装饰后,被传入Decorator中的func失去了bound属性,自然也不会自动注入实例。

    class Decorator(object):
        def __init__(self, func):
            self.func = func
    
        def __call__(self, *args, **kwargs):
            print("Decorator: self: {}, args: {}, kwargs: {}".format(self, args, kwargs))
            return self.func(*args, **kwargs)
    
    class Decorated(object):
        @Decorator
        def foo(self, *args, **kwargs):
            print("Method Decorated: self: {}, args: {}, kwargs: {}".format(self, args, kwargs))
    
    Decorated().foo('hello, world')
    # Decorator: self: <__main__.Decorator object at 0x7f978aeb0290>, args: ('hello, world',), kwargs: {}
    # Method Decorated: self: hello, world, args: (), kwargs: {}
    

    function、bound method与unbound method的区别

    上一节我们说到了bound method和unboud method,本小节将对这些概念进行具体说明。

     class Cls(object):
    
         def foo(self):
            pass
     instance = Cls()
    
     print 'foo' in Cls.__dict__                # True
     print 'foo' in instance.__dict__           # False
    
     print Cls.foo              # <unbound method Cls.foo>
     print instance.foo         # <bound method Cls.foo of <__main__.Cls object at 0x7ff05ddef390>>
     print Cls.__dict__['foo']  # <function foo at 0x7ff05dde98c0>
    

    我们发现,foo是以function类型存在类的__dict__中的,但通过实例访问是会得到一个bound method,通过类访问是会得到一个unbound method。这是因为在python中,所有的函数都是非资料描述器(no data descriptor)。通过类或实例访问时,会被__get__方法会包装一层返回unbound method或bound method,而unboud和bound的区别在于method的im_self是否为空。bound method会自动将instance作为第一个入参,而unbound method对参数不做任何处理。
    在上一小节的例子中,foo作为Decorator的一个成员变量,其type是一个function,所以不会自动地注入实例。

    Cls.foo会被翻译成Cls.__dict __[‘foo’].__get__(None, Cls),返回一个unbound method(im_self is None)
    instance.foo会被翻译成type(instance).__dic __[‘foo’].__get__(instance, type(instance)),返回一个bound method(im_self == instance)
    instance.foo(args, kwargs) 等价于 Cls.foo(instance, args, kwargs)

    修改方法

    通过分析,我们发现根本原因在于,被装饰的foo作为Decorator实例的成员变量,其类型是一个function,失去了bound属性,不能自动地将instance实例注入到函数的第一个参数中去。为了解决这个,我们可以将Decorator实现成一个描述器,当被类或实例访问时,通过types.MethodType将Decorator实例包装成一个method。

    class Decorator(object):
    
        def __init__(self, func):
            self.func = func
    
        def __get__(self, instance, owner):
            return types.MethodType(self, instance, owner)
    
        def __call__(self, *args, **kwargs):
            print("Decorator: self: {}, args: {}, kwargs: {}".format(self, args, kwargs))
            return self.func(*args, **kwargs)
    

    参考文献

    The Inside Story on New-Style Classes
    python - Instancemethod or function? - Stack Overflow
    Chris’s Wiki :: blog/python/HowFunctionsToMethods
    Descriptor HowTo Guide — Python 2.7.15 documentation
    python - How can I decorate an instance method with a decorator class? - Stack Overflow
    Glossary — Python 2.7.15 documentation

    相关文章

      网友评论

          本文标题:Python装饰器类的使用——bound/unbound met

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