python 魔法方法补充(__setattr__,__getattr__,__getattribute__)
python 魔法方法补充
1 getattribute (print(ob.name) -- obj.func())当访问对象的属性或者是方法的时候触发
class F(object):
def __init__(self):
self.name = 'A'
def hello(self):
print('hello')
def __getattribute__(self, item):
print('获取属性,方法',item)
return object.__getattribute__(self,item)
a = F()
print(a.name)
a.hello()
获取属性,方法 name
A
获取属性,方法 hello
hello
2 getattr 拦截运算(obj.xx),对没有定义的属性名和实例,会用属性名作为字符串调用这个方法
class F(object):
def __init__(self):
self.name = 'A'
def __getattr__(self, item):
if item == 'age':
return 40
else:
raise AttributeError('没有这个属性')
f = F()
print(f.age)
# 40
3 setattr 拦截 属性的的赋值语句 (obj.xx = xx)
class F(object):
def __setattr__(self, key, value):
self.__dict__[key] = value
a = F()
a.name = 'alex'
print(a.name)
如何自定义私有属性:
class F(object): # 基类--定义私有属性
def __setattr__(self, key, value):
if key in self.privs:
raise AttributeError('该属性不能改变')
else:
self.__dict__[key] = value
class F1(F):
privs = ['age','name'] # 私有属性列表
# x = F1()
# x.name = 'egon' # AttributeError: 该属性不能改变
# x.sex = 'male'
class F2(F):
privs = ['sex'] # 私有属性列表
def __init__(self):
self.__dict__['name'] = 'alex'
# y = F2()
# y.name = 'eva'
getitem , setitem, delitem
class F(object):
def __getitem__(self,item):
print(item)
def __setitem__(self,key,value):
print(key,value)
def __delitem__(self,key):
print(key)
f = F()
f['b']
f['c'] = 1
del f['a']
读书使人心眼明亮