优先级:getattribute() > getattr()
意思是一般的“.”操作调用的就是__geattribute__(),例如
class A:
def __init__(self, name, age):
self.name = name
self.age = age
a = A('xcy', 23)
print(a.name)
这里就是直接调用的__getattribute__(),如果我们想对访问属性做一些限制,比如说随便询问别人的年龄是不好的
class A:
def __init__(self, name, age):
self.name = name
self.age = age
def __getattribute__(self, item):
if item == 'age':
return "it's secret!"
a = A('xcy', 23)
print(a.age)
如果要对不存在属性做相应的处理,一般在__getattr__()中做操作
class A:
def __init__(self, name, age):
self.name = name
self.age = age
def __getattr__(self, item):
if item not in self.__dict__:
raise AttributeError('wrong!')
a = A('xcy', 23)
print(a.gender)