How might one change the syntax of python list indexing?

北战南征 提交于 2020-01-06 03:21:10

问题


After asking this question, it received a comment about how you could do something like this:

>>> def a(n):
        print(n)
        return a
>>> b = a(3)(4)(5)
3
4
5

Is it possible to use this or similar concepts to make it possible to index lists like my_list(n) instead of my_list[n]?


回答1:


You'd have to use a custom class, and give it a __call__ special method to make it callable. A subclass of list would do nicely here:

class CallableList(list):
    def __call__(self, item):
        return self[item]

You cannot use this to assign to an index, however, only item access works. Slicing would require you to use to create a slice() object:

a = CallableList([1, 2, 3])
a(2)
a(slice(None, 2, None))

nested = CallableList([1, 2, CallableList([4, 5, 6])])
nested(2)(-1)

For anything more, you'd have to create a custom Python syntax parser to build an AST, then compile to bytecode from there.




回答2:


the parentheses in my_list() are treated as a function call. If you want, you could write your own class that wraps a list and overwrite the call method to index into the list.

class MyList(object):

    def __init__(self, alist):
        self._list = alist

    def __call__(self, index):
        return self._list[index]

>>> mylist = MyList(['a','b','c','d','e','f'])
>>> mylist(3)
'd'
>>> mylist(4)
'e'



回答3:


You could create a function that returns a lambda function:

def make_callable(some_list):
    return lambda x: some_list[x]

original_list = [ 1, 2, 3, 4 ]
callable_list = make_callable(original_list)

print(callable_list(1)) # Prints 2


来源:https://stackoverflow.com/questions/23754775/how-might-one-change-the-syntax-of-python-list-indexing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!