08.2 __getattr__ 和 __getattribute__

# -*- coding: utf-8 -*-
# @Time : 2021/8/1 18:01
# @Author : zy7y
# @Gitee : https://gitee.com/zy7y
# @File : getattr.py
# @Project : PythonBooks

"""
__getattr__: 获取属性,当找不到属性时 会调用这个方法
__getattribute__: 获取属性时,都会调用这个方法,其内部其实还是调用了__getattr__
"""

class User:
    def __init__(self, age):
        self.age = age


    def __getattr__(self, item):
        print(item, "__getattr__")

    def __getattribute__(self, item):
        print(item, "__getattribute__")


if __name__ == '__main__':
    print(User(18).name)
    print(User(18).age)
作者:zy7y
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/zy7y/p/15087248.html