__getitem__

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dqchouyang/article/details/79952996

代码怎么写的时候才能调用python的內建函数__getitem__

>>> class A():
...     def __getattribute__(self, value):
...         print("come on")
...         return value
... 
>>> 
>>> 
>>> a = A()
>>> a.get('key')
come on
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>>

上面的例子虽然不是很恰当,但是我得到了我想要的答案,并且 如果a是字典的话a[‘key’]也是会触发__getitem__
同理,一般对象还有下面的内建函数,大家可以了解下喽。

[‘add‘, ‘class‘, ‘contains‘, ‘delattr‘, ‘dir‘, ‘doc‘, ‘eq‘, ‘format‘, ‘ge‘, ‘getattribute‘, ‘getitem‘, ‘getnewargs‘, ‘gt‘, ‘hash‘, ‘init‘, ‘iter‘, ‘le‘, ‘len‘, ‘lt‘, ‘mod‘, ‘mul‘, ‘ne‘, ‘new‘, ‘reduce‘, ‘reduce_ex‘, ‘repr‘, ‘rmod‘, ‘rmul‘, ‘setattr‘, ‘sizeof‘, ‘str‘, ‘subclasshook‘]

猜你喜欢

转载自blog.csdn.net/dqchouyang/article/details/79952996
今日推荐