ITPub博客

首页 > 应用开发 > > python的getattr, getattribute

python的getattr, getattribute

作者:lakefront 时间:2019-09-11 15:53:51 0 删除 编辑

python的getattr 用于normal attribute lookup fails的情况, 例如某 attribute不存在

而getattribute 会拦截所有的atttribute lookup 操作,不论这个attribute 存在与否

代码更清楚

class P:
    x = 'a'
    def __init__(self,n=0):
        self.n = n

    def __getattr__(self,name):
        return("__geattr__ will be called when normal attribute get failed")

    '''
    def __getattribute__(self, name):
        return("__getattribute__ will be called always")
    '''

def test_():
    p = P()
    print(p.x)
    print(p.n)
    print(p.__dict__)
    #with parameter, equals p.__dict__
    print(vars(p))
    #searching for a attribute which is not exist
    print(p.f)
    print(getattr(p, 'n'))
    print(getattr(p, 'x'))

test_()
a
0
{'n': 0}
{'n': 0}
__geattr__ will be called when normal attribute get failed
0
a
class B:
    x = 'ba'
    def __init__(self,n=100):
        self.n = n

    def __getattr__(self,name):
        return("__geattr__ will be called when normal attribute get failed")

    def __getattribute__(self, name):
        return("__getattribute__ will be called always")

def test2_():
    b = B()
    print(b.x)
    print(b.n)
    print(b.__dict__)
    #With parameter, equals to b.__dict__
    print(vars(b))
    #searching for a attribute which is not exist
    print(b.f)
    print(getattr(b, 'n'))
    print(getattr(b, 'x'))

test2_()

运行结果

__getattribute__ will be called always
__getattribute__ will be called always
__getattribute__ will be called always
__getattribute__ will be called always
__getattribute__ will be called always
__getattribute__ will be called always
__getattribute__ will be called always


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2491/viewspace-3165459/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-05

  • 博文量
    99
  • 访问量
    625