Python系列交替

2024-09-29 21:51:19 发布

您现在位置:Python中文网/ 问答频道 /正文

for i in range(10):

for i in 0 .. 9:

我如何“超载”。在

我发现range()对象不简洁易读。pascal符号/语法(范围(包括。。inclusive)http://rigaux.org/language-study/syntax-across-languages-per-language/Pascal.html)只是更容易阅读。在

我在pathlib模块https://docs.python.org/3/library/pathlib.html中看到它重载(?)/字符。在


Tags: 对象inorghttpforhtml语法符号
1条回答
网友
1楼 · 发布于 2024-09-29 21:51:19

虽然Python没有..运算符,但可以定义一个中缀运算符,如下所示:

class Infix:
    def __init__(self, function):
        self.function = function
    def __ror__(self, other):
        return Infix(lambda x, self=self, other=other: self.function(other, x))
    def __or__(self, other):
        return self.function(other)
    def __rlshift__(self, other):
        return Infix(lambda x, self=self, other=other: self.function(other, x))
    def __rshift__(self, other):
        return self.function(other)
    def __call__(self, value1, value2):
        return self.function(value1, value2)

现在,选择一个有意义的名称,如until,您就完成了:

^{pr2}$

或者

for i in (2 |until| 4):
    print(i)

不幸的不是我的主意,见this brilliant post for the original idea。在

相关问题 更多 >

    热门问题