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
  • 相关阅读:
    vps安装wordpress遇到的问题(lnmp)
    RING0,RING1,RING2,RING3
    CentOS 下配置CUPS
    怎样解决VS2013模块对于SAFESEH 映像是不安全的
    【转】VC6.0打开或者添加工程文件崩溃的解决方法
    QWidget QMainWindow QDialog 三个基类的区别
    在C语言中,double、long、unsigned、int、char类型数据所占字节数
    拷贝构造函数
    “浅拷贝”与“深拷贝”
    常用软件列表
  • 原文地址:https://www.cnblogs.com/hanxiaomeng/p/12711696.html
Copyright © 2011-2022 走看看