1.__setattr__()
是在属性赋值时被访问,比如我们调用instance.x=1时,并将x存储到__dict__
中
class Person(object):
def __init__(self):
self.name = "wang"
self.age = 18
self.male = True
def __setattr__(self, key, value):
print("*"*50)
print("setting:{}, with:{}".format(key, value))
print("current __dict__ : {}".format(self.__dict__))
return object.__setattr__(self,key,value) # 因为子类重写父类方法,所以要返回父类该方法完成在__dict__的注册,父类的__setattr__本质上是完成了·self.__dict__[key] = value·
person = Person()
由于return在print之后,所以打印的结果会错一步。
2.注意下例中不能使用self.dict = {}
,会出现递归调用
class Foo(object):
def __init__(self):
object.__setattr__(self, 'dict', {})
# self.dict = {} # 会调用setattr,递归调用错误
def __setattr__(self, key, value):
self.dict = {'k1':'v1'}
print(key,value)
def __getattr__(self, item):
print(item)
return 'df'
obj = Foo()
# obj.x = 123
# 对象.xx setattr会执行
3.setattr应用:
1.将字典转换为类的属性
class Foo(object):
def __init__(self):
self.values = {
'x':'wang',
'y':'wei',
}
for k,v in self.values.items():
setattr(self,k,v)
obj = Foo()
print(obj.x)
参考:
https://zhuanlan.zhihu.com/p/101004827?from_voters_page=true