_ getattr_()
当调用一个不存在的属性时,就会触发__getattr__()
class Foo:
x = 1
def __init__(self, y):
self.y = y
def __getattr__(self, item):
print("执行__getattr__()")
print("不存在",item)
f1 = Foo(10)
print(f1.x)#调用存在的属性不会触发__getattr__()
f1.dsa#因为dsa属性不存在,所以会触发__getattr__(),将f1传给self,dsa传给item
_ delattr_()
删除一个属性的时候会触发__delattr__()
class Foo:
x = 1
def __init__(self, y):
self.y = y
def __getattr__(self, item):
print("执行__getattr__()")
print("不存在", item)
def __delattr__(self, item):
print("执行__delattr__()")
#del self.item 这样写会进入死递归
self.__dict__.pop(item)#这是删除操作的本质
f1 = Foo(10)
del f1.y
_ setattr_()
在改动属性或新增属性的时候会触发__setattr__()
class Foo:
x = 1
def __init__(self, y):
self.y = y
def __getattr__(self, item):
print("执行__getattr__()")
print("不存在", item)
def __delattr__(self, item):
print("执行__delattr__()")
self.__dict__.pop(item)
def __setattr__(self, key, value):
print("执行__setattr__()")
self.key = value#这样写会进入死递归
self.__dict__[key] = value
f1 = Foo(10)
这些双下划綫开头的方法都是类内置的方法,可以通过dir(object)函数来查看
所有类内函数,都是如果有定义先调用定义的,没有定义则调用默认的
相对而言__getattr__()函数更有用,其他两个函数用的比较少
双下划綫开头的方法,只有在类的实例调用的时候才会触发
作用实例
1.当属性不存在时,不报错
class Foo:
x = 1
def __init__(self, y):
self.y = y
def __getattr__(self, item):
print("执行__getattr__()")
print("不存在", item)
f1 = Foo(10)
f1.age
2.所有属性都要求是字符串
class Foo:
x = 1
def __init__(self, y):
self.y = y
def __setattr__(self, key, value):
if type(value) is str:
self.__dict__[key] = value
print("设置成功")
else:
print("属性内容必须是字符串,设置失败")
f1 = Foo(10)
f2 = Foo("CJJ")
3.所有属性都不允许删除
class Foo:
x = 1
def __init__(self, y):
self.y = y
def __delattr__(self, item):
print("所有属性不允许删除")
f1 = Foo(10)
f1.name = "CJJ"
del f1.name