美文网首页
8-2 getattr和getattribute

8-2 getattr和getattribute

作者: 正在努力ing | 来源:发表于2018-08-26 15:34 被阅读0次
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是在实例化之后,查找属性时执行的,不管找不找得到,只要执行属性查找,就会自动调用这个函数,所以能不重写就不要重写

相关文章

网友评论

      本文标题:8-2 getattr和getattribute

      本文链接:https://www.haomeiwen.com/subject/ageoiftx.html