python - 我可以为 __getitem__() 和 __setitem__() 提供任何代码块吗?
问题描述
在 python操作员文档中,__getitem__(a, b)
据说:
返回索引b处a的值。
我知道使用__getitem__(x, i)
makex[i]
等同于type(x).__getitem__(x, i)
.
在下面的示例中,当我尝试"Taco Bell"
在__getitem__(self, items)
函数中打印字符串时它仍然有效。
class Test(object):
# This function prints the type
# of the object passed as well
# as the object item
def __getitem__(self, items):
print ("Taco Bell")
# Driver code
test = Test()
test[5]
test[5:65:5]
test['GeeksforGeeks']
test[1, 'x', 10.0]
test['a':'z':2]
test[object()]
印刷:
Taco Bell
Taco Bell
Taco Bell
Taco Bell
Taco Bell
Taco Bell
这是什么意思?我可以__getitem__()
在python中给出任何代码块吗?
解决方案
这种方法:
def __getitem__(self, items):
print ("Taco Bell")
隐式返回None
,就像任何其他没有显式return
语句的 Python 函数/方法一样。所以你正在返回一些东西。
>>> t = Test()
>>> t[0] is None
Taco Bell
True
>>> t['foo'] is None
Taco Bell
True
无论如何,是的,__getitem__
方法(或任何其他方法)中的代码可以是任意的,你可以做任何你想做的事情。当然,你应该对给定的参数做一些事情(例如,用它来以某种方式查找一个项目),但你也可以很好地忽略它。这是否有意义取决于您。