zoukankan      html  css  js  c++  java
  • python属性查找顺序

     1 import numbers
     2 
     3 class IntField:
     4     # 数据描述符
     5     def __get__(self, instance, owner):
     6         return self.value
     7 
     8     def __set__(self, instance, value):
     9         if not isinstance(value, numbers.Integral):
    10             raise ValueError('int value need')
    11         if value < 0:
    12             raise ValueError('positive value need')
    13         self.value = value
    14 
    15     def __delete__(self, instance):
    16         pass
    17 
    18 class NonDataIntField:
    19     # 非数据属性描述符
    20     def __get__(self, instance, owner):
    21         return self.value
    22 
    23 class User:
    24     # age = IntField()
    25     age = NonDataIntField()
    26 
    27 if __name__=='__main__':
    28     user = User()
    29     user.__dict__['age'] = 'abc'
    30     print(user.__dict__)
    31     print(getattr(user, 'age'))

    输出:

    {'age': 'abc'}
    abc

    查找顺序:

    先查找__getattribute__: 

      1.查找数据描述符__get__

      2.查找实例__dict__

      3.查找基类

        若是非数据描述符访问其__get__

        否则查找基类__dict__

    没找到再查找__getattr__

    否则抛出异常AttributeError

  • 相关阅读:
    HDU 2757 Ocean Currents
    HDU 2704 Bulletin Board
    HDU 2234 无题I
    HDU 3638 Go , SuSu
    HDU 1199 Color the Ball
    HDU 1430 魔板
    PL/SQL例外的介绍
    表分区介绍
    移动表空间数据文件
    long\lob\bfile类型介绍
  • 原文地址:https://www.cnblogs.com/icekx/p/9188211.html
Copyright © 2011-2022 走看看