python魔法函数之__getattr__与__getattribute__

getattr

在访问对象的属性不存在时,调用__getattr__,如果没有定义该魔法函数会报错

class Test:
    def __init__(self, name, age):
        self.name = name 
        self.age = age  
    
    def __getattr__(self, item):
        print(item)   // noattr
        return 'aa'


test = Test('rain', 25)
print(test.age)   // 25
print(test.noattr) //aa
getattribute

访问对象任何属性(即使属性不存在)都会调用__getattribute__

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   04__getattr__与__getattribute__.py
@Time    :   2018/12/18 21:06:50
@Author  :   Rain 
@License :   (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
@Desc    :   None
'''

# here put code


class Test:
    def __init__(self, name, age):
        self.name = name 
        self.age = age
    
    def __getattr__(self, item):
        print(item)
        return 'aa'

    def __getattribute__(self, item):  # 尽量不要使用它
        print('访问属性了')
        return 'bbb'

test = Test('rain', 25) 
print(test.age)
print(test.noattr)

结果:

猜你喜欢

转载自www.cnblogs.com/raind/p/10140108.html