有没有办法在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
答案 0 :(得分:2)
检查一下,希望对你有帮助。这是强制进行类型检查的方法之一。
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
如果是None
或string
,则会引发AssertionError
AssertionError:值必须是Interger Type
但是如果你确实需要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:值必须是Interger Type