python对象构造函数出现问题



es。

class item:
def __init__(self, number:int):
self.number = number
a = item("ciao")

当我实例化对象时,我希望确保name参数的类型是字符串,否则会引发异常。"名称:str";实际上并没有检查参数是否为指定类型的

根据文档:

Python运行时不强制执行函数和变量类型注释。它们可以由第三方工具使用,例如类型方格、IDE、短绒等

如果您想强制执行类型,可以使用isinstance()函数来执行。

class item:
def __init__(self, number: int):
if not isinstance(number, int):
raise TypeError('Value should be of type int')
self.number = number

注释不会向开发人员添加更多有关预期信息的信息。这是通过一个非正式的契约来完成的,因为正如我们所知,简单的注释不包含语法含义,但在运行时可以访问,所以我们可以实现一个能够从函数注释中检查类型的泛型装饰器。

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

这可能是您想要的。您可以使用isinstance()来检查它是否是一个字符串。我不习惯解释,所以我不知道写得对不对,但逻辑是。

class item:
def __init__(self, name):
if isinstance(name, str):
self._name = name
else:
self._name = None
raise Exception

a = item('ciai')