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
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值