繁体   English   中英

python对象构造函数的问题

[英]Problem with the python object constructor

es.

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

当我实例化对象时,我想确保名称参数是字符串类型,否则会引发异常。 “name: str”实际上并不检查参数是否为指定类型

根据文档

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

注释不会向开发人员添加更多关于预期信息的信息。 这是通过非正式合同完成的,因为我们知道,简单的注解不包含句法含义,但在运行时可以访问,因此我们可以实现一个通用的装饰器,它能够从函数注解中检查类型。

def ensure_annotations(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_annotations
    def __init__(self, number: int):
        self.number = number

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

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


a = item('ciai')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM