Python __get__() __getattr__() __getattribute__()

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




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值