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']


浙公网安备 33010602011771号