类的内置方法(二 )

__getattr__与__getattribute__

class Foo:
    def __init__(self,x):
        self.x=x
    def __getattr__(self, item):
        print('执行getattr')
    def __getattribute__(self, item):
        print('执行getattribute')
f=Foo(10)
f.x
f.xx
#输出为
#执行getattribute
#执行getattribute

内置方法(一)中说过当属性存在时不会调用__getatrr__,只有属性不存在时才调用__getatrr__

而上面的例子说明无论属性存不存在都会调用__getatrribute__,

但是上面的例子似乎在访问不存在的属性时没有调用__getatrr__,为什么?继续看下面例子

class Foo:
    def __init__(self,x):
        self.x=x
    def __getattr__(self, item):
        print('执行getattr')
    def __getattribute__(self, item):
        print('执行getattribute')
        raise AttributeError    #注意这行加入的抛出属性错误
f=Foo(10)
f.x
f.xx
#输出为
执行getattribute
执行getattr
执行getattribute
执行getattr
由上面一个例子可以看出,无论属性存不存在,都会调用__getatrribute__,但只有在抛出AttributeError时才会再次调用__getatrr__函数.

__item__

class Foo:
    def __init__(self,x):
        self.x=x
    def __getitem__(self, item):
        print('执行getitem')
        print(self.__dict__[item])
    def __setitem__(self, key, value):
        print('执行setitem')
        self.__dict__[key]=value
    def __delitem__(self, key):
        print('执行delitem')
        self.__dict__.pop(key)

f=Foo(10)
print(f.__dict__)
f['x']
f['y']=1
print(f.__dict__)
del f['y']
print(f.__dict__)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值