python中的getattribute 、getattr、setattr方法详解

 更新时间:2023年11月03日 10:14:25   作者:惊瑟  
这篇文章主要介绍了python中的getattribute 、getattr、setattr方法详解,python类中默认有一些特殊方法,这篇文章记录一下特殊方法的功能及用法,需要的朋友可以参考下

一、__getattribute__()

顾名思义,当访问object的属性会调用该方法,可以测试:

class A(object):

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

    def __getattribute__(self, attr):
        print("__getattribute__ is called")
        try:
            return super().__getattribute__(attr)
        except AttributeError:
            print(f'have no attr of {attr}')
            
if __name__ == '__main__':
    a = A('jyz',200)
    print(a.name)
    print(a.age)
		print(a.gender)

输出:

__getattribute__ is called
jyz
__getattribute__ is called
200
__getattribute__ is called
have no attr of gender
None

可以看出,当我们通过object.attrname的形式访问实例属性时,实际上我们是通过__getattribute__得到了该属性,是不是联想到了OOP中封装的思想?别急,下面会看到更多的oop设计思想。值得一提的是,在重写__getattribute__()方法时,一定要知道你在做什么,否则可能导致无法正确访问实例对象。另外,官方文档建议始终使用基类方法来设置属性,否则会陷入无限递归,最终栈溢出:

在这里插入图片描述

比如可以尝试:

class A(object):

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

    def __getattribute__(self, attr):
       return self.name
       
if __name__ == '__main__':
    a = A('jyz',200)
    print(a.name)

输出:

  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

究其原因,是因为当使用self.name访问属性时会调用__getattribute__,而__getattribute__又要访问self.name,因此会无限递归下去。正确的做法是使用基类方法,对于该例子由于继承的是基类,因此使用super().__getattribute__(attr)或object.__getattribute__(self,attr)均可。

二、__setattr__()

实例初始化过程中,为实例属性赋值时会调用该方法。

class A(object):

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

    def __getattribute__(self, attr):
        print("__getattribute__ is called")
        try:
            return super().__getattribute__(attr)
        except AttributeError:
            print(f'have no attr of {attr}')

    def __setattr__(self, key, value):
        print(f"__setattr__() is called, key is {key}")
        object.__setattr__(self, key, value)

输出:

__setattr__() is called, key is name
__setattr__() is called, key is age

与__getattribute__同理,在__setattr__中也尽量使用基类的该方法来设置一些属性,否则可能发生无限递归。

三、__getattr__()

从字面意思理解跟__getattribute__差不多,事实上,该方法是__getattribute__的补充,当访问某些属性不存在,或**__getattribute__显示地抛出AttributeError**,会自动转到该方法做进一步处理。

在这里插入图片描述

可以测试:

class A(object):

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

    def __getattr__(self, attr):
        print(f"__getattr__() is called,but {attr} is not exist!")
   
if __name__ == '__main__':
    a = A('jyz',200)
    print(a.gender)

输出:

__getattr__() is called,but gender is not exist!
None

测试通过主动抛出异常的方式触发__getattr__():

class A(object):

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

    def __getattribute__(self, attr):
        if attr not  in ['name','age']:
            raise AttributeError
        else:
            return object.__getattribute__(self, attr)

    def __getattr__(self, attr):
        print(f"__getattr__() is called,but {attr} is not exist!")

if __name__ == '__main__':
    a = A('jyz',200)
    print(a.name)
    print(a.gender)
    

输出:

jyz
__getattr__() is called,but gender is not exist!
None

可以看到,上面两种方式都可以触发,__getattr__()。

到此这篇关于python中的getattribute 、getattr、setattr方法详解的文章就介绍到这了,更多相关getattribute 、getattr、setattr方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python程序中设置HTTP代理

    Python程序中设置HTTP代理

    本文主要给大家简单讲解了下http代理的概念以及如何在Python程序中设置http代理的方法,非常的详细,有需要的小伙伴可以参考下
    2016-11-11
  • Python语言检测模块langid和langdetect的使用实例

    Python语言检测模块langid和langdetect的使用实例

    今天小编就为大家分享一篇关于Python语言检测模块langid和langdetect的使用实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-02-02
  • Django 实现图片上传和显示过程详解

    Django 实现图片上传和显示过程详解

    这篇文章主要介绍了Django 实现图片上传和显示过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07
  • python调用matplotlib模块绘制柱状图

    python调用matplotlib模块绘制柱状图

    这篇文章主要为大家介绍了python调用matplotlib模块绘制柱状图,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-10-10
  • Python APScheduler执行使用方法详解

    Python APScheduler执行使用方法详解

    在本篇文章里小编给大家整理的是一篇关于Python APScheduler执行使用方法的相关内容,有兴趣的朋友们可以学习下。
    2020-12-12
  • Python中如何将一个类方法变为多个方法

    Python中如何将一个类方法变为多个方法

    这篇文章主要介绍了Python中如何将一个类方法变为多个方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • Python异常之常见的Bug类型解决方法

    Python异常之常见的Bug类型解决方法

    这篇文章主要介绍了Python异常之常见的Bug类型解决方法,主要分享一些粗心导致和知识不熟练导致的语法错误以及被迫掉坑等内容,文章介绍非常详细需要的小伙伴可以参考一下
    2022-03-03
  • python中树与树的表示知识点总结

    python中树与树的表示知识点总结

    在本篇文章里小编给大家分享的是关于python中树与树的表示的相关知识点,需要的读者们学习下吧。
    2019-09-09
  • Numpy数组的组合与分割实现的方法

    Numpy数组的组合与分割实现的方法

    本文主要介绍了Numpy数组的组合与分割实现的方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-08-08
  • Python发起请求提示UnicodeEncodeError错误代码解决方法

    Python发起请求提示UnicodeEncodeError错误代码解决方法

    这篇文章主要介绍了Python发起请求提示UnicodeEncodeError错误代码解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04

最新评论