【问题标题】:How to allow multiple types of arguments in function?如何在函数中允许多种类型的参数?
【发布时间】:2021-02-04 22:53:58
【问题描述】:
def extraction(content: str,  channels: List[Color]=[Color.Red]):
  pass

第二个参数 channels 是一个颜色列表。但是,如果我也想允许通道作为 str 参数的可能性呢?在这种情况下,它变成:

def extraction(content: str,  channels: str=None):
      pass

是否可以将两种定义合并为一个函数定义?

【问题讨论】:

  • 可选的是你的朋友。另请注意,Python 类型是完全可选的。没有什么能阻止您将任何类型传递给该函数。
  • 如果你想说channels 可以是List[color]str,那就是Union[List[Color], str]。但是,您不能根据类型设置不同的默认值。你必须做一些类似默认None的事情,然后通过其他方式决定它应该有什么价值。另请注意,您应该usually not have a mutable default argument。它不会总是导致问题,但它为某些错误打开了大门。
  • @Carcigenicate,如果使用Union,那么我应该使用instanceOf来检查函数体中是List还是str?
  • 你可以。类型的运行时检查通常是一种气味。如果函数的第二个参数需要不同的类型,那么完全定义不同的函数可能更有意义,然后让一个函数遵循另一个函数,或者第三个辅助函数。
  • 我明白了。但我确实经常看到在其他人的代码中使用了 instaneOf。是对的吗?这不是它的最佳用例吗?

标签: python


【解决方案1】:
def extraction(content: str,  channels) :
    if type (channels) is str :
        print ('channels is a string.')
    if type (channels) is list :
        print ('channels is a list.')

extraction ('testing', ['one, two three'])

【讨论】:

  • 所以,type函数可以代替instanceOf。比后者有什么好处?
  • @marion 我不知道。
  • 这实际上没有任何好处。它只是完全消除了类型提示。如果需要类型提示,请使用 Union 类型。
猜你喜欢
  • 2021-10-04
  • 2012-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
相关资源
最近更新 更多