8-2 getattr和getattribute

2018-08-26  本文已影响0人  正在努力ing
from datetime import date,datetime

class User:
    def __init__(self,name,birth,info):
        self.name = name
        self.birth = birth
        self.info = info
        # self.age = 0

    def __getattr__(self, item):
        return self.info[item]


user = User("zhou",date(year=1987,month=1,day=1),info={"hight":170,"weight":57,"age":31})
print(user.age)
>>> 31

在实例中查找不到age属性时,会调用getattr魔法函数,
但是

class User:
    def __init__(self,name,birth,info):
        self.name = name
        self.birth = birth
        self.info = info
        # self.age = 0

    def __getattr__(self, item):
        return self.info[item]

    def __getattribute__(self, item):
        return "boo"


user = User("zhou",date(year=1987,month=1,day=1),info={"hight":170,"weight":57,"age":31})
print(user.birth) 
>>> boo

getattribute是在实例化之后,查找属性时执行的,不管找不找得到,只要执行属性查找,就会自动调用这个函数,所以能不重写就不要重写

上一篇 下一篇

猜你喜欢

热点阅读