【问题标题】:python3: how to enable strong typing?python3:如何启用强类型?
【发布时间】:2018-06-08 15:12:42
【问题描述】:

有没有办法在 python3 中获得真正的强类型,这样当使用错误的类型时会出现运行时错误? 请参见以下示例:

def pick(k:int = None):
    if k: print("value: ", k)
    else: print("no value")

pick()
pick(1000)
pick("error")

这给出了以下输出:

no value       <- can be accepted, and for this example it would be useful
value:  1000
value:  error  <- here should come a runtime error

【问题讨论】:

    标签: python-3.x strong-typing


    【解决方案1】:

    检查一下,希望对您有所帮助。这是强制类型检查的方法之一。

    def pick(k:int = None):
         assert isinstance(k, int), 'Value Must be of Interger Type'
         print("value: ", k) if k else print("no value")  # Single Line Statement
    

    如果是Nonestring,它将引发AssertionError

    AssertionError: 值必须是整数类型

    但是,如果你真的需要 ValueError 被加薪,那么

     def pick(k:int = None):
         if not isinstance(k, int):
             raise ValueError('Value Must be of Interger Type')
    
         print("value: ", k)  if k else print("no value") # Single line statement
    

    例外

    ValueError:值必须是整数类型

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 2014-07-26
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 2020-12-18
      • 2011-04-30
      相关资源
      最近更新 更多