概述
__getattr__
当你请求获取一个并没有定义的属性时,python将会调用此方法。下图示例当中,Student
没有__ getattr __
方法,我们获取student.name
和student.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__的区别所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复