【问题标题】:Python: How to fix parameter type? [duplicate]Python:如何修复参数类型? [复制]
【发布时间】:2018-12-28 19:37:40
【问题描述】:

如何在 Python 中修复参数类型?

def truncus(fill=int):
    return [i for i in range(fill)]

【问题讨论】:

  • 你可以使用注解给类型hints,但是python不会强制它们。 def truncus(fill: int)
  • “修复”是指“修复”还是“固定到位”?换句话说,你是在问“我的代码坏了,我该如何让它做我想做的事?”还是您在问“我如何确保只能将整数传递给truncus,而不是其他?”?
  • 你在浪费时间,真的。只需使用已传递给 truncus 的任何内容,然后让异常传播 - 结果将 完全 与您输入检查 fill 相同:它将在运行时引发 TypeError

标签: python python-3.x


【解决方案1】:
def truncus(fill):
  if type(fill) != int:
    raise Exception("A non-integer value was passed to truncus.")
  return [i for i in range(fill)]

【讨论】:

  • 坦克,但有其他方法吗?
  • 我认为isinstance 而不是type() ==。例如,这将允许我们指定我们想要一个 Iterable
  • 这至少应该使用isinstance并提出TypeError
  • Python 是动态类型的。如果你真的想要静态类型,我会研究一种静态类型的语言。
  • @Carcigenicate 在某些情况下类型检查(我的意思是正确完成的类型检查)是有意义的。但我同意这里只是浪费大家的时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-26
  • 2017-10-12
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
  • 2020-05-22
  • 2021-06-23
相关资源
最近更新 更多