• 面向对象-描述符


    描述符使用

    Foo接管了Bar的x值,当x值被操作的时候都调用Foo相应的get/set/delete操作

    class Foo:
        def __get__(self,instance,owner):
            print('===>get',instance,owner)
        def __set__(self,instance,value):
            print('===>set',instance,value)
        def __delete__(self, instance):
            print('===>delete',instance)
    
    class Bar:
        x = Foo()
        def __init__(self,n):
            self.x = n
    
    b1 = Bar(10)
    print(b1.__dict__)
    print(Bar.__dict__)
    print(b1.x)
    '''
    ===>set <__main__.Bar object at 0x0000022A4A214D68> 10
    {}
    {'__module__': '__main__', 'x': <__main__.Foo object at 0x0000022A4A214C50>, '__init__': <function Bar.__init__ at 0x0000022A4A1F6C80>, '__dict__': <attribute '__dict__' of 'Bar' objects>, '__weakref__': <attribute '__weakref__' of 'Bar' objects>, '__doc__': None}
    ===>get <__main__.Bar object at 0x0000022A4A214D68> <class '__main__.Bar'>
    None
    '''
    
    class Foo:
        def __get__(self,instance,owner):
            print('===>get',instance,owner)
        def __set__(self,instance,value):
            print('===>set',instance,value)
        def __delete__(self, instance):
            print('===>delete',instance)
    
    class Bar:
        x = Foo()
        def __init__(self,n):
            self.x = n
    
    # print(Bar.x)
    # Bar.x = 1 #不触发描述符,因为类属性优先级更高,如果不注释,后面的语句也不触发描述符
    b1 = Bar(10)
    print(b1.x)
    del b1.x
    '''
    ===>set <__main__.Bar object at 0x000001D368C14CF8> 10
    ===>get <__main__.Bar object at 0x000001D368C14CF8> <class '__main__.Bar'>
    None
    ===>delete <__main__.Bar object at 0x000001D368C14CF8>
    '''
    

    描述符优先级

    1. 类属性
    2. 数据描述符---》至少实现了get、set方法
    3. 实例属性
    4. 非数据描述符 ----》没有set方法
    5. 找不到的属性触发__getattr__()
    class Foo:
        def __get__(self,instance,owner):
            print('===>get',instance,owner)
        def __set__(self,instance,value):
            print('===>set',instance,value)
        def __delete__(self, instance):
            print('===>delete',instance)
    
    class Bar:
        x = Foo()
        def __init__(self,n):
            self.x = n
    
    # print(Bar.x)
    Bar.x = 1 #不触发描述符,因为类属性优先级更高
    '''
    
    Process finished with exit code 0
    '''
    
  • 相关阅读:
    VC++ 调用C# dll 回调函数,实现MQTT协议客户端通信
    如何正确获取ADO连接MySql的连接字符串(转载)
    SQL 操作
    MFC如何添加背景图片(转载)
    MFC CFont 要释放的资源总结
    MFC控件 Edit,控制只能输入数字和小数点
    VC MFC 获取 IP地址和MAC地址程序
    MFC CString 转 CTime
    vc mfc 写excel文件,包括数据和图表
    ADO方式操作access数据库
  • 原文地址:https://www.cnblogs.com/chrrydot/p/9822905.html
Copyright © 2020-2023  润新知