zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    解决GOOGLE不能用的办法
    Elmah错误日志工具
    Linq 更改主键值
    qcow2、raw、vmdk等镜像格式
    Ceph相关博客、网站(256篇OpenStack博客)
    Delphi中inherited问题
    Qt qss一些伪装态,以及margin与padding区别
    Qt双缓冲机制:实现一个简单的绘图工具(纯代码实现)
    写出一篇好博文需要用到的工具
    最短路径启蒙题
  • 原文地址:https://www.cnblogs.com/hanxiaomeng/p/12711696.html
Copyright © 2011-2022 走看看