Python魔法方法__getattr__、__setattr__、__getattribute__的介绍
一、__getarribute__方法
__getattribute__(self, name):拦截所有的属性访问操作
>>> class Person: ... def __init__(self, name): ... self.name = name ... def __getattribute__(self, attr): ... if attr == 'name': ... return '姓名:' + super().__getattribute__(attr) ... else: ... return raise AttributeError('属性%s不存在!' % attr) ... >>> p = Person('韩晓萌') >>> p.name '姓名:韩晓萌' >>> p.age Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 属性age不存在!
二、__getattr__方法
__getattr__(self, name):拦截对不存在属性的访问操作
>>> class Person: ... def __init__(self, name): ... self.name = name ... def __getattr__(self, attr): ... raise AttributeError('没有属性%s!' % attr) ... >>> p = Person('韩晓萌') >>> p.name '韩晓萌' >>> p.age Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in __getattr__ AttributeError: 没有属性age!
三、__setattr__方法
__setattr__(self, attr, value):拦截所有属性的赋值操作
>>> class Person: ... def __init__(self, name): ... self.name = name ... def __setattr__(self, attr, value): ... if attr == 'name': ... if not isinstance(value, str): ... raise TypeError('name的值必须是字符串!') ... self.__dict__[attr] = value ... else: ... super().__setattr__(attr, value) >>> p = Person(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in __init__ File "<stdin>", line 7, in __setattr__ TypeError: name的值必须是字符串! >>> p = Person('韩晓萌') >>> p.name '韩晓萌' >>> p.name = 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in __setattr__ TypeError: name的值必须是字符串! >>> p.name = '杨超越' >>> p.name '杨超越' >>> p.age = 21 >>> p.age 21