您可以使用property
或@property
来创建使用数组语法的内容吗?在代码中,这看起来像:
x = ExampleClass()
x.y[6] #x.y is a property, 6 is passed as an arg to getter function
感谢
答案 0 :(得分:1)
您可以通过将y
设为容器类型来执行此操作:
>>> class A(object):
... def __getitem__(self, index):
... return 2 * index
...
>>> a = A()
>>> a[3]
6
>>> class ExampleClass(object):
... def __init__(self):
... self.y = A()
...
>>> x = ExampleClass()
>>> x.y[6]
12