__getattr__()
函数__getattr__()
函数是特殊函数__getattribute__()
函数__getattribute__()
在查找真正要访问的属性之前就被调用了,无论该属性是否存在。__getattribute__()
要特别注意,因为如果你在它里面不知何故再次调用了__getattribute__()
,你就会进入无穷递归。为了避免这种情况,如果你想要访问任何它需要的属性,应该总是调用祖先类的同名方法:比如super(obj, self).__getattribute__(attr)
class Count(object):
def __init__(self, min, max):
self.min = min
self.max = max
self.current = None
def __getattribute__(self, item):
print(type(item), item)
if item.startswith('cur'):
raise AttributeError
return object.__getattribute__(self, item)
# or you can use ---return super().__getattribute__(item)
obj1 = Count(1, 10)
print(obj1.min)
print(obj1.max)
print(obj1.current)
class Count(object):
def __init__(self, mymin, mymax):
self.mymin = mymin
self.mymax = mymax
self.current = None
def __getattr__(self, item):
self.__dict__[item] = 0
return 0
def __getattribute__(self, item):
if item.startswith('cur'):
raise AttributeError
return object.__getattribute__(self, item)
# or you can use ---return super().__getattribute__(item)
# note this class subclass object
obj1 = Count(1, 10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)
# 1
# 10
# 0
本系列文章和代码已经作为项目归档到github,仓库地址:jumper2014/PyCodeComplete。大家觉得有帮助就请在github上star一下,你的支持是我更新的动力。什么?你没有github账号?学习Python怎么可以没有github账号呢,快去注册一个啦!