python隐式调用方法_python – 为什么在隐式__getitem __-调用时没有调用__getattribute__?...

在尝试包装任意对象时,我遇到了字典和列表的问题.调查,我设法提出了一段简单的代码,其行为我根本不理解.我希望你们中的一些人可以告诉我发生了什么:

>>> class Cl(object): # simple class that prints (and suppresses) each attribute lookup

... def __getattribute__(self, name):

... print 'Access:', name

...

>>> i = Cl() # instance of class

>>> i.test # test that __getattribute__ override works

Access: test

>>> i.__getitem__ # test that it works for special functions, too

Access: __getitem__

>>> i['foo'] # but why doesn't this work?

Traceback (most recent call last):

File "", line 1, in

TypeError: 'Cl' object has no attribute '__getitem__'

解决方法:

Magic __methods __()被特别处理:它们在内部分配给类型数据结构中的“槽”以加速它们的查找,并且它们仅在这些槽中被查找.如果插槽为空,则会收到错误消息.

In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the __getattribute__() method even of the object’s metaclass.

[…]

Bypassing the __getattribute__() machinery in this fashion provides significant scope for speed optimisations within the interpreter, at the cost of some flexibility in the handling of special methods (the special method must be set on the class object itself in order to be consistently invoked by the interpreter).

标签:python,magic-methods

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值