es.
class item:
def __init__(self, number:int):
self.number = number
a = item("ciao")
當我實體化物件時,我想確保名稱引數是字串型別,否則會引發例外。“name: str”實際上并不檢查引數是否為指定型別
uj5u.com熱心網友回復:
根據檔案:
Python 運行時不強制執行函式和變數型別注釋。它們可以被第三方工具使用,例如型別檢查器、IDE、linter 等。
如果您想強制執行型別,您可以使用isinstance()函式來執行此操作。
class item:
def __init__(self, number: int):
if not isinstance(number, int):
raise TypeError('Value should be of type int')
self.number = number
uj5u.com熱心網友回復:
注釋不會向開發人員添加更多關于預期資訊的資訊。這是通過非正式合同完成的,因為我們知道,簡單的注解不包含句法含義,但在運行時可以訪問,因此我們可以實作一個通用的裝飾器,它能夠從函式注解中檢查型別。
def ensure_types(function):
signature = inspect.signature(function)
parameters = signature.parameters
@wraps(function)
def wrapped(*args, **kwargs):
bound = signature.bind(*args, **kwargs)
for name, value in bound.arguments.items():
annotation = parameters[name].annotation
if annotation is inspect._empty:
continue
if not isinstance(value, annotation):
raise TypeError(
"{}: {} doesn't actually check that the parameter"
"is of the specified type.".format(name, annotation)
)
function(*args, **kwargs)
return wrapped
class item:
@ensure_types
def __init__(self, number: int):
self.number = number
uj5u.com熱心網友回復:
這可能就是你想要的。您可以使用isinstance()它來檢查它是否是一個字串。我不習慣 exeptions,所以我不知道這是否寫對,但邏輯是。
class item:
def __init__(self, name):
if isinstance(name, str):
self._name = name
else:
self._name = None
raise Exception
a = item('ciai')
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/337523.html
上一篇:如何使用其他python檔案中的函式,我將其命名為Features.py我想在main.py的類中使用該函式
下一篇:從不同的URL格式決議域名
