我是靠谱客的博主 兴奋蜜粉,最近开发中收集的这篇文章主要介绍Python中__getattr__和__getattribute__的区别,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

__getattr__

当你请求获取一个并没有定义的属性时,python将会调用此方法。下图示例当中,Student没有__ getattr __方法,我们获取student.namestudent.age这两个参数都可以成功获取,但是当我们尝试得到student.sex参数时,python抛出了属性异常AttributeError: 'Student' object has no attribute 'sex'

class Student:
    def __init__(self):
        self.name = 'xiaohu'
        self.age = 24

student = Student()
print(student.name) # xiaohu
print(student.age) # 24
print(student.sex) # AttributeError: 'Student' object has no attribute 'sex

我们给Student类加上__ getattr __方法

class Student:
    def __init__(self):
        self.name = 'xiaohu'
        self.age = 24

    def __getattr__(self, item):
        self.__dict__[item] = None
        return None


student = Student()
print(student.name)
print(student.age)
print(student.sex)

虽然student.sex属性并没有定义,__ getattr __方法返回的值仍然被打印出来,

# 打印结果
xiaohu
24
None

__ getattribute __

如果在你的类当中,存在__ getattribute __方法,Python将会为每个属性调用这个方法无论它存在与否。那我们使用__ getattribute __ 方法的目的是?主要还是为了控制属性的访问,并且增加它们的安全性。如下图所示,任何人只要访问sex的属性,将抛出定义的异常。

class Student:
    def __init__(self):
        self.name = 'xiaohu'
        self.age = 24
        self.sex = None

    def __getattribute__(self, item):
        if item == 'sex':
            raise AttributeError
        return super().__getattribute__(item)


student = Student()
print(student.name)
print(student.age)
print(student.sex)

输出:

Traceback (most recent call last):
  File "D:/Python/PyCharm/workspace/week4/day18_模块/test.py", line 20, in <module>
    print(student.sex)
  File "D:/Python/PyCharm/workspace/week4/day18_模块/test.py", line 13, in __getattribute__
    raise AttributeError
AttributeError
xiaohu
24

总结

当你的类里面同时有__ getattr ____ getattribute __这两个魔法方法时,__ getattribute __方法将会首先被调用.但是如果 __ getattribute __方法引发了AttributeError异常,那么这个异常会被忽略,取而代之__ getattr __方法被调用。

class Student:
    def __init__(self):
        self.name = 'xiaohu'
        self.age = 24
        self.sex = None

    def __getattr__(self, item):
        self.__dict__[item] = None
        return None

    def __getattribute__(self, item):
        if item == 'sex':
            raise AttributeError
        return super().__getattribute__(item)


student = Student()
print(student.name)
print(student.age)
print(student.sex)

输出:

xiaohu
24
None

最后

以上就是兴奋蜜粉为你收集整理的Python中__getattr__和__getattribute__的区别的全部内容,希望文章能够帮你解决Python中__getattr__和__getattribute__的区别所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(96)

评论列表共有 0 条评论

立即
投稿
返回
顶部