• 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属性的时候被自动调用

  • 相关阅读:
    oracle行转列
    JVM设置空间大小
    Spring AOP 业务权限管理
    清晨漫步
    pull解析xml(android)
    今昔何昔
    Spring: Document root element "beans", must match DOCTYPE root "null
    xfire
    心之所向
    Oracle数据库连接
  • 原文地址:https://www.cnblogs.com/shunguo/p/15706160.html
Copyright © 2020-2023  润新知