• python小知识-属性查询优先级(如果有同名类属性、数据描述符、实例属性存在的话,实例>类>数据描述符)


    https://www.cnblogs.com/Jimmy1988/p/6808237.html

    https://segmentfault.com/a/1190000006660339

    https://blog.csdn.net/u013679490/article/details/54767152

    1.getattribute() 无条件调用

    2.数据描述符(定义了__get__\__set__方法的类的实例)

      --由1的getattribute()调用【注,会将数据描述符转换成:当前类名.__dict__['x'].__get__(instance,owner)】

      --如果我们重新定义了__getattribute__方法,可能会导致没办法调用数据描述符

    3.当前对象的字典

      --如果数据描述符合当前对象字典的属性重名,那么数据描述符会覆盖之

    4.当前类的字典

    5.非数据描述符(只定义了__get__方法的类的实例)

    6.父类的字典

    7.__getattr__()

    class Desc:
        def __init__(self,name,nametype):
            print('i am desc!')
            self.name = name
            self.nametype = nametype
    
        def __get__(self, instance, owner):
            return instance.__dict__[self.name]
    
        def __set__(self, instance, value):
            if isinstance(value,self.nametype):
                instance.__dict__[self.name] = value
            else:
                raise TypeError('excepted an {}'.format(self.nametype))
    
        def __delete__(self, instance):
            del instance.__dict__[self.name]
    
    
    class A():
    
        # name = Desc('name', str)
        # age = Desc('age',int)
        # name = 'jack'
        def __getattr__(self, item):
            print('no %s' %item)
            # return  self.__dict__[item]
    #
    a = A()
    # a.name='alex'
    # print(a.name)
    # a.name = 'taibei'
    print(a.name)
    # a.name = 123
    # print(a.name)
    利用数据描述符检查赋值属性的正确与否!!!
  • 相关阅读:
    页面存在多个setInterval
    ios 常见兼容问题
    微信开发常用代码
    jq右侧划出
    常用 css rem 根字体
    weinre使用教程
    CSS属性大全
    微信H5页面前端开发,大多数人都会遇到的几个兼容性坑
    后台管理系统页面欣赏
    微信公众号开发文档
  • 原文地址:https://www.cnblogs.com/wuchenggong/p/9220851.html
Copyright © 2020-2023  润新知