【问题标题】:Handling function arguments with multiple possible types处理具有多种可能类型的函数参数
【发布时间】:2022-06-14 21:42:48
【问题描述】:

我想定义一个带有两个参数的函数,第一个是字符串列表,第二个是要打印的字符串的选择。第二个参数应该默认为“all”,这意味着打印所有行。

起初这看起来微不足道:

def f(x, pageRange="all"):
    """
    pageRange can be an iterable or a list of integers
    """
    for i, line in enumerate(x):
        if (pageRange=="all")|(i in pageRange) :
            print(line)

lines = ["abc", "efg", "hij"]

f(lines, range(1,2))
f(lines, [0,2])
f(lines)

但第三次调用返回错误:

TypeError: 'in <string>' requires string as left operand, not int

因为第一遍布尔表达式的第二部分是0 in "all"

使用hasattr(pageRange, "__iter__") 添加第二次检查不起作用,因为“all”也是可迭代的。

知道如何解决这个问题吗?

【问题讨论】:

  • 你有|,应该是oror 运算符短路,因此如果 pageRange"all",则不会评估第二个条件。

标签: python


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-23
  • 2017-12-09
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-09
相关资源
最近更新 更多