zoukankan      html  css  js  c++  java
  • __getattr__与__getattribute__的区别

    https://docs.python.org/zh-cn/3/reference/datamodel.html#customizing-attribute-access

    __getattr__

    __getattribute__

    __setattr__
    __getattr__与__getattribute__均是一般实例属性截取函数(generic instance attribute interception method),其中,__getattr__可以用在python的所有版本中,
    而__getattribute__只可以用到新类型类中(New-style class),其主要的区别是__getattr__只截取类中未定义的属性,而__getattribute__可以截取所有属性

    实例instance通过instance.name访问属性name,只有当属性name没有在实例的__dict__或它构造类的__dict__或基类的__dict__中没有找到,才会调用__getattr__
    当属性name可以通过正常机制追溯到时,__getattr__是不会被调用的。如果在__getattr__(self, attr)存在通过self.attr访问属性,会出现无限递归错误。

    object.__getattribute__(self, name) 实例`instance`通过`instance.name`访问属性`name`,`__getattribute__`方法一直会被调用,无论属性`name`是否追溯到。
    如果类还定义了`__getattr__`方法,除非通过`__getattribute__`显式的调用它,或者`__getattribute__`方法出现`AttributeError`错误,否则`__getattr__`方法不会被调用了。
    如果在`__getattribute__(self, attr)`方法下存在通过`self.attr`访问属性,会出现无限递归错误。

    class Test:
        def __getattr__(self, item):
            # 当我们访问属性的时候,如果属性不存在(出现AttrError),该方法会被触发
            print('调用__getattr__方法')
            # object.__getattribute__(self, item)
            # return 100
    
        def __getattribute__(self, item):
            # 查找属性的时候第一时间触发该方法找属性
            print('调用__getattribute__方法')
            # return 100
            # return super().__getattribute__(item)
    
        def __setattr__(self, key, value):
            # 这个方法在给对象设置属性的时候触发
            print('调用__setattr__方法')
            # print(key, value)
    
    
        def __delattr__(self, item):
            # 这个方法在删除属性的时候会被触发
            print('调用__delattr__方法')
    
            if item == 'age':
                pass
            else:
                super().__delattr__(item)
    
    t = Test()
    t.name = 'hh'
    print(t.name)
    __delattr__
  • 相关阅读:
    hdu 4309(最大流+枚举状态)
    hdu 1565+hdu 1569(最大点权独立集)
    hdu 3657(最大点权独立集)
    hdu 3491(最小割+拆点)
    hdu 4394(bfs)
    An Introduction to Numerical Analysis Example 6.1
    陶哲轩谈数学家的合作(来自陶哲轩在数学家Gowers的博文“Is massively collaborative mathematics possible?”上的评论)
    拉格朗日插值多项式之间的递推关系
    三角形的余弦定理
    三角形的余弦定理
  • 原文地址:https://www.cnblogs.com/ella-li/p/14225021.html
Copyright © 2011-2022 走看看