• python __setattr__ __getattr__


    class A:
        def __init__(self,width,heigth):
            self.width = width
            self.heigth = heigth
        def __setattr__(self,name, value):
            print("----set %s attribute" %name)
            if name == "size":
                print("controll sieze attribute")
                self.width = value
                # print(self.width)
            else:
                self.__dict__[name] = value
        def __getattr__(self,name):
            print("---get %s attribute " %name)
    
    
    a = A(3,4)
    a.size = 100
    print(a.width)
    print(a.__dict__)
    ----set width attribute
    ----set heigth attribute
    ----set size attribute
    controll sieze attribute
    ----set width attribute
    100
    请按任意键继续. . .

    __getattribute__(self, name) : 当程序访问对象的name属性时会自动调用

    __getattr__(self,name) : 当程序访问对象的name属性且改属性不存在时被自动调用

    __setattr__(self,name): 当程序对对象的name属性赋值的时候被自动调用

    __delattr__(self, name) :当程序删除对象的name属性的时候被自动调用

  • 相关阅读:
    leetcode144 longest-palindromic-substring
    数据结构之二叉树
    数据结构之堆
    数据结构之图
    数据结构之排序
    数据结构之动态规划
    14 RPC
    数据结构之字符串
    数据结构之散列表
    16 中间人攻击
  • 原文地址:https://www.cnblogs.com/shunguo/p/15706160.html
Copyright © 2020-2023  润新知