是否可以在 Python 中制定自己的语法规则?

Is it possible to make own syntax rules in Python?

显然 Numpy 为其列表提供了一种特殊的语法。也就是说,我遇到了符号 myarray[:, 4]。我试图在 Numpy 中找到数组的来源,但没有成功。 (我只找到了一些 C.h 头文件和一个已编译的库。)

有人知道如何创建自己的语法吗?

这是一个使用元组伪造多维索引的简短演示:

>>> a={(1,2):'hi', (3,4):'there'}
>>> a[1,2]; a[3,4]
'hi'
'there'

numpy 仅使用简单的 python 语法 - 大概 - __getitem____setitem__ 的智能实现(参见 python docs)。

您可以通过实现自己的 __getitem__ 方法轻松使用此表示法:

class Object(object):
    def __getitem__(self, item):
        print item

看看它在做什么:

>>> o = Object()
>>> o[:,1:2]
(slice(None, None, None), slice(1, 2, None))

语法是Python语言的一部分。 Slicing syntax支持1个或多个切片:

extended_slicing ::=  primary "[" slice_list "]"
slice_list       ::=  slice_item ("," slice_item)* [","]

[...] If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key.

Numpy 利用了该功能;您需要做的就是实现 object.__getitem__() special method 并处理 slice() 对象的元组。

现在,Numpy 项目确实在要求这成为可能方面发挥了重要作用;这同样适用于 ... 语法和 Ellipsis 对象的使用,以及 numeric method hooks.

的限制

例如,新的 dedicated @ and @= syntax 也是 Numpy 社区特别要求的。因此,从本质上讲,如果您有一个引人注目的用例和足够大的使用该语言的社区,您可以提出新的语法并将其添加到该语言中。