python __getattr__, __setattr__

调用类中原本没有定义的属性时候,调用__getattr__

class Cat(object):
    def __init__(self):
        self.name = "jn"

    def __getattr__(self, item):
        return "tm"


cat = Cat()
print(cat.name)
print(getattr(cat, 'name'))
print("*" * 20)
print(cat.age)
print(getattr(cat, 'age'))

#对实例的属性进行赋值的时候调用__setattr__

class Dict(dict):

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Dict' object has no attribute '%s'" % key)

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

d = Dict(a=1, b=2)
print (d['a'])
print (d.a) 
d.a = 100 
print (d['a'])

 

猜你喜欢

转载自www.cnblogs.com/honglingjin/p/12108722.html