zoukankan      html  css  js  c++  java
  • getattribute方法,Python属性访问拦截器的用法

    __getattribute__()方法是属性访问时的拦截器,每当访问属性的时候,会先执行这个方法,然后再执行访问属性的操作步骤,可以用来记录属性访问的log。

    简单说,想知道谁访问了你的某个变量,就用__getattribute__()方法

    代码示例如下:

     

    class Itcast(object):
        def __init__(self, subject1):
            self.subject1 = subject1
            self.subject2 = "haha"

        def __getattribute__(self, obj): #重写父类的__getattribute__方法,形参obj是访问的属性,是一个属性名字字符串

            print("*******>%s"%obj)
            if obj == "subject1":        #如果属性名是subject1,可以做一些操作
                print("log subject1")
                return "python"
            else:              #else必须写,如果不写,那subject2以及show方法就访问不到了
                temp = object.__getattribute__(self,obj)   #调用父类的__getattribute__方法
                print("------>%s"%str(temp))
                return temp      #不写return的话,show方法无法执行

        def show(self):
            print("this is Itcast")


    s = Itcast("python")
    print(s.subject1)
    print(s.subject2)
    s.show()             #show方法执行的时候也会先走属性拦截器方法

    千万注意__getattribute__方法里面不能再使用self.的方式调用属性或者方法,因为你这样用,等于执行self.这句话的时候,又要先执行__getattribute__方法,执行这个方法的时候,执行到self.又开始执行__getattribute__方法,那你就死循环到这里了。

    如果需要对某些属性进行记录log,可以按照参考下面的代码,修改print(item)为记录log的代码块

    class D(object):
        def __init__(self):
            self.num = 0

        def __getattribute__(self, item):
            if item == "num":
                print(item)        #如果访问的属性名字叫num,则记录log
                temp = object.__getattribute__(self, item)   #调用父类方法把原来num的值返回去
                return temp
            else:
                temp = object.__getattribute__(self, item)
                return temp


    a = D()
    print(a.num)

  • 相关阅读:
    Apache Thrift的简单使用
    ExternalInterface的简单使用方法
    Android各种屏幕分辨率(VGA、HVGA、QVGA、WQVGA、WVGA、FWVGA) 具体解释
    白话经典算法系列之六 高速排序 高速搞定
    HTML学习_01
    Codeforces Round #256 (Div. 2) A. Rewards
    activity
    自己生产签名和数字证书的方法
    Android项目目录结构
    Android程序的安装和打包
  • 原文地址:https://www.cnblogs.com/sy_test/p/12054078.html
Copyright © 2011-2022 走看看