之前写的,现在好像不可以用了

映射setattr,getattr,delattr合集_赋值映射setattr,getattr,delattr合集_赋值_02

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()

View Code

映射类:怎么玩:

映射setattr,getattr,delattr合集_赋值映射setattr,getattr,delattr合集_赋值_02

a = A()
A.__getattribute__(a,"name1")
a.__getattribute__("name1")
getattr(A,"name1")
getattr(a,"name1")

View Code -----------------------------------------------------------------------------------------------------------------------------------------