映射setattr,getattr,delattr合集
之前写的,现在好像不可以用了
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Foo: def __init__(self): print("初始化") def __setattr__(self, key, value): """ 属性赋值操作时 self.name = "33" f1.age = 11 # 属性不存在就创建 setattr(f1, "name","张三") """ print("调用%s方法"%("setattr")) print(key,value) def __delattr__(self, item): """ 删除属性的时候 del f1.name del self.name delattr(f1, "namasssssssae") """ print("调用%s方法" % ("delattr")) print(item) def __getattr__(self, item): """ 调用属性的时候 self.name f1.name getattr(f1, "nameq") """ print("调用%s方法"%("getattr")) print(item) if __name__ == "__main__": f1 = Foo()
映射类:怎么玩:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
a = A() A.__getattribute__(a,"name1") a.__getattribute__("name1") getattr(A,"name1") getattr(a,"name1")
-----------------------------------------------------------------------------------------------------------------------------------------