https://blog.csdn.net/weixin_45912307/article/details/115535385
# -- encoding: utf-8 --
# @time: 2021/4/6 23:29
# @Author: jsonLiu
# @Email: xxxxxxx@qq.com
# @file: customattributeaccess
import logging
class CustomAttrVisit(object):
def __getattr__(self, item):
# 访问属性时,如果属性不存在(出现AttrError),该方法会被触发
print("__getattr__被调用")
try:
# super().__getattribute__(item) # super继承父类不需self
object.__getattribute__(self,item) # object调实例需要self
except Exception as e:
logging.error("call __getattr__ error:{}".format(e))
def __getattribute__(self, item):
# 访问属性的时候,第一时间触发该方法去找属性
print("__getattribute__被调用")
return super().__getattribute__(item) # 必须return,否则打印为None
def __setattr__(self, key, value):
# 给对象设置属性时触发
if key == 'age':
super().__setattr__(key,18)
else:
print("__setattr__被调用")
super().__setattr__(key,value)
def __delattr__(self, item):
# 删除属性时被触发
print("__delattr__被调用")
super().__delattr__(item)
CAV = CustomAttrVisit()
CAV.name = 'python' # 触发setattr
print(CAV.name) # 触发 getattribute
print(CAV.age) # __getattribute__和__getattr__被调用
del CAV.age