zoukankan      html  css  js  c++  java
  • 浅谈Python 中 __getattr__与__getattribute__的区别

    __getattr__与__getattribute__均是一般实例属性截取函数(generic instance attribute interception method),其中,__getattr__可以用在python的所有版本中,而__getattribute__只可以用到新类型类中(New-style class),其主要的区别是__getattr__只截取类中未定义的属性,而__getattribute__可以截取所有属性,下面用代码进行说明:

    (1)__getattr__

    class c:
        def __init__(self,value):
            self.data=value
        def __getattr__(self,name):
            print('getattr...
     intercept %s'% name)
        @property
        def p(self):
            print(" i'm not intercepted, so you can see me")
    >>> x.data
    1
    >>> x.a
    getattr...
     intercept a
    >>> x.b
    getattr...
     intercept b
    >>> x.p
     i'm not intercepted, so you can see me

    从上面可以看出,对于类c中已定义的实例属性data,p,均显示了出来,而对于未定义的a,b都进行了拦截。

    (2)__getattribute__函数

    将上面的代码中的__getattr__换成__getattribute__,其他的不做变动

    >>> class c:
        def __init__(self,value):
            self.data=value
        def __getattribute__(self,name):
            print('getattr...
     intercept %s'% name)
        @property
        def p(self):
            print(" i'm intercepted, so you can not see me")
    >>> x=c(2)
    >>> x.a
    getattr...
     intercept a
    >>> x.b
    getattr...
     intercept b
    >>> x.p
    getattr...
     intercept p
    >>> x.data
    getattr...
     intercept data

    调用实例的属性,可以发现,全部被__getattrbute__予以了拦截。

    ##### 愿你一寸一寸地攻城略地,一点一点地焕然一新 #####
  • 相关阅读:
    1.1 HTML5简介
    MATLAB基础知识——1.1MATLAB系统变量
    初识MATLAB
    Z-Stack
    [C语言]关于struct和typedef struct
    [Zigbee]定时器1
    常用数论算法
    SPFA&邻接表 PASCAL
    kruskal算法-Pascal
    懒惰的JY--关于遍历
  • 原文地址:https://www.cnblogs.com/johnyang/p/10464208.html
Copyright © 2011-2022 走看看