python魔法方法之__setattr__()/__setattr__,__delattr__,__getattr__

介绍

本质上是内部的触发函数,不需要显示的调用
介绍xxxattr、__xxxattr__的区别。
xxxattr是内置函数,调用方法为xxxattr()
__xxxattr__是对象的方法,调用方法为object.xxxattr()
明确对象时,优先使用__xxxattr.

python魔法方法之__setattr__():

https://zhuanlan.zhihu.com/p/101004827?from_voters_page=true

setattr,delattr,getattr 到底干了什么?:

https://zhuanlan.zhihu.com/p/62569340

setattr()与__dict__

由于每次类实例进行属性赋值时都会调用__setattr__(),所以可以重载__setattr__()方法,来动态的观察每次实例属性赋值时__dict__()的变化。下面的Fun类重载了__setattr__()方法,并且将实例的属性和属性值作为__dict__的键-值对:

class Fun:
    def __init__(self):
        self.name = "Liu"
        self.age = 12
        self.male = True
        
    def __setattr__(self, key, value):
        print("*"*50)
        print("setting:{},  with:{}".format(key[], value))
        print("current __dict__ : {}".format(self.__dict__))
        # 属性注册
        self.__dict__[key] = value
fun = Fun()    

通过在__setattr__()中将属性名作为key,并将属性值作为value,添加到了__dict__中,得到的结果如下:

**************************************************
setting:name,  with:Liu
current __dict__ : {
    
    }
**************************************************
setting:age,  with:12
current __dict__ : {
    
    'name': 'Liu'}
**************************************************
setting:male,  with:True
current __dict__ : {
    
    'name': 'Liu', 'age': 12}

可以看出,init()中三个属性赋值时,每次都会调用一次__setattr__()函数。

猜你喜欢

转载自blog.csdn.net/qq_15821487/article/details/126548345