python 对象构造函数的问题
Problem with the python object constructor
es.
class item:
def __init__(self, number:int):
self.number = number
a = item("ciao")
当我实例化对象时,我想确保名称参数是字符串类型,否则会引发异常。
"name: str" 实际上不检查参数是否为指定类型
这可能就是您想要的。您可以使用 isinstance()
来检查它是否是一个字符串。我不习惯exeptions,所以我不知道这样写对不对,但是逻辑是这样的。
class item:
def __init__(self, name):
if isinstance(name, str):
self._name = name
else:
self._name = None
raise Exception
a = item('ciai')
根据 documentation:
The Python runtime does not enforce function and variable type
annotations. They can be used by third party tools such as type
checkers, IDEs, linters, etc.
如果您想强制执行此类型,您可以使用 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
es.
class item:
def __init__(self, number:int):
self.number = number
a = item("ciao")
当我实例化对象时,我想确保名称参数是字符串类型,否则会引发异常。 "name: str" 实际上不检查参数是否为指定类型
这可能就是您想要的。您可以使用 isinstance()
来检查它是否是一个字符串。我不习惯exeptions,所以我不知道这样写对不对,但是逻辑是这样的。
class item:
def __init__(self, name):
if isinstance(name, str):
self._name = name
else:
self._name = None
raise Exception
a = item('ciai')
根据 documentation:
The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.
如果您想强制执行此类型,您可以使用 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