简体   繁体   English

python对象构造函数的问题

[英]Problem with the python object constructor

es. es.

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

When I instantiate the object I would like to make sure that the name parameter is of type string and otherwise an exception is raised.当我实例化对象时,我想确保名称参数是字符串类型,否则会引发异常。 "name: str" doesn't actually check that the parameter is of the specified type “name: str”实际上并不检查参数是否为指定类型

As per the documentation :根据文档

The Python runtime does not enforce function and variable type annotations. Python 运行时不强制执行函数和变量类型注释。 They can be used by third party tools such as type checkers, IDEs, linters, etc.它们可以被第三方工具使用,例如类型检查器、IDE、linter 等。

If you would like to enforce the type you can use isinstance() function to do so.如果您想强制执行类型,您可以使用isinstance()函数来执行此操作。

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

Annotations do not add more than information to the developer about the expected information.注释不会向开发人员添加更多关于预期信息的信息。 This is done through an informal contract because, as we know, simple annotations do not contain syntactic meaning but are accessible at runtime, so we can implement a generic decorator that is capable of checking types from the function annotations.这是通过非正式合同完成的,因为我们知道,简单的注解不包含句法含义,但在运行时可以访问,因此我们可以实现一个通用的装饰器,它能够从函数注解中检查类型。

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

This might be what you want.这可能就是你想要的。 You can use isinstance() to check if it is a string.您可以使用isinstance()来检查它是否是字符串。 I am not used to exeptions, so I don't know if that is written right, but the logic is.我不习惯 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