__getattr__和__getattribute__笔记

__author__ = "Mr-Li"
__date__ = "2020/1/7 11:04 下午"


class User(object):

    def __init__(self, name, birthday):
        self.name = name
        self.birthday = birthday

    def __getattr__(self, item):
        """ 1、查找不到属性的时候调用 """
        return item

    def __getattribute__(self, item):
        """ 2、查找属性的时候首先调用 """
        return item


if __name__ == '__main__':
    user = User("lzh", "1994-10-23")
    # user没有sex属性,则会返回属性名
    print(user.name)
    print(getattr(user, "name"))

你可能感兴趣的:(__getattr__和__getattribute__笔记)