https://blog.youkuaiyun.com/yiifaa/article/details/78068962
class Employee(object):
def __init__(self,username,age):
self.username = username
self.age = age
#当通过'.'运算符访问属性时调用该方法
def __getattribute__(self, item):
return super(Employee,self).__getattribute__(item)
#当通过'[]'运算符访问属性时调用的方法,在这里调用了'.'运算符方法的实现
def __getitem__(self, item):
return super(Employee, self).__getattribute__(item)
#当访问不存在的属性时,Python解释器会报错(AttributeError:'xxx' object has no attribute 'xxx')
#通过覆盖实现'__getattr__'回调接口可以解决此问题
def __getattr__(self, item):
return '您访问的属性不存在'
employee = Employee('hello',32)
print(employee.username)
#通过实现'__getitem__'回掉接口现在支持'[]'运算符
print(employee['username'])
bucunzai = employee.aa
print(bucunzai)
#'__getattribute__'与'__getattr__'的区别:
#当访问属性时(包括没有的)都会首先调用'__getattribute__'方法
#当访问的属性不存在时,则会调用'__getattr__'方法
class Dept(object):
def __init__(self,name):
self.name = name
#owner是拥有此属性的类变量(不是实例变量),instance则是该类变量(owner)的实例
#self就是那个self比如这里是Dept类的实例
def __get__(self, instance, owner):
print(type(self))
print(type(instance))
print(owner)
print(type(owner))
return 'Dept'
class Company(object):
#一定要作为类属性,不能作为实例属性
#descriptor的实例自己访问自己是不会触发__get__,而会触发__call__,只有descriptor作为其他类
的类属性才有意义
dept = Dept('Jack Ma')
x = Company()
print(x.dept)
print(type(x.dept))
#当通过类变量来访问时,instance为None
print(Company.dept)
输出:
hello
hello
您访问的属性不存在
<class '__main__.Dept'>
<class '__main__.Company'>
<class '__main__.Company'>
<class 'type'>
Dept
<class '__main__.Dept'>
<class '__main__.Company'>
<class '__main__.Company'>
<class 'type'>
<class 'str'>
<class '__main__.Dept'>
<class 'NoneType'>
<class '__main__.Company'>
<class 'type'>
Dept