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

你可能感兴趣的:(面试题的大海)