如何改变python列表索引的语法? [英] How might one change the syntax of python list indexing?

查看:346
本文介绍了如何改变python列表索引的语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在询问这个问题之后,它收到了关于你的评论可以做这样的事情:

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

是否可以使用这个或类似的概念来索引像 my_list(n)这样的列表而不是 my_list [ n]

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]?

推荐答案

你必须使用自定义类,并给它一个< a href =https://docs.python.org/3/reference/datamodel.html#object.__call__ =nofollow> __ call __ special method 使其可调用。 list 的子类在这里可以很好地做到:

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]

您无法使用此分配给索引,但只有 access 项才有效。切片需要你用来创建一个 slice()对象:

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)

除此之外,您还必须创建一个自定义Python语法解析器来构建AST,然后从那里编译为字节码。

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

这篇关于如何改变python列表索引的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆