Python 的 __get__描述符

 问题的引出:一篇文章让你彻底搞清楚Python中self的含义

""""

https://www.jb51.net/article/86749.htm
https://python3-cookbook.readthedocs.io/zh_CN/latest/c08/p09_create_new_kind_of_class_or_instance_attribute.html


"""


class C(object):
    """
   存在了__get__的方法的类称之为描述符类

    descriptor 的实例自己访问自己是不会触发__get__,而会触发__call__,只有 descriptor 作为其它类的属性的时候才会触发 __get___
    """
    a = 'abc'

    def __get__(self, instance, owner):
        print("__get__() is called", instance, owner)
        return self


class C2(object):
    # 为了使用一个描述器,需将这个描述器的实例作为类属性放到一个类的定义中.
    d = C()  # descriptor 的实例自己访问自己是不会触发__get__,而会触发__call__,只有 descriptor 作为其它类的属性的时候才会触发 __get___


if __name__ == '__main__':
    # 不触发
    c = C()
    print(c.a)

    # 触发
    c2 = C2()
    print(c2)  # <__main__.C2 object at 0x00CB0DC0>
    print(c2.d.a)

abc
<__main__.C2 object at 0x00CB0DC0>
__get__() is called <__main__.C2 object at 0x00CB0DC0>
abc

你可能感兴趣的:(Python,Python的__get__,__get__描述符,Python,__get__,Python,的描述符)