__getattr__和__setattr__

getattr 拦截运算(obj.xx),对没有定义的属性名和实例,会用属性名作为字符串调用这个方法

class F(object):
        def __init__(self):
            self.name = 'A'
    
        def __getattr__(self, item):
            if item == 'age':
                return 40
            else:
                raise AttributeError('没有这个属性')
    
    f = F()
    print(f.age)

setattr 拦截 属性的的赋值语句 (obj.xx = xx)


class F(object):

    def __setattr__(self, key, value):
        self.__dict__[key] = value

a = F()
a.name = 'alex'
print(a.name)
print(a.__dict__)
原文地址:https://www.cnblogs.com/an5456/p/11738291.html