简体   繁体   English

输入子类的提示

[英]Type hint for instance of subclass

I want to allow type hinting using Python 3 to accept instances which are children of a given class. 我想允许使用Python 3进行类型提示来接受作为给定类的子节点的实例。 I'm using the enforce module to check the function typing. 我正在使用强制模块来检查函数类型。 Eg: 例如:

import abc
class A(metaclass=abc.ABCMeta)
      pass
class B(A)
      def __init__(self,a)
      self.a = a
      pass
x = B(3)

@enforce.runtime_validation
def function(x:A)
     print(x.a)

but it seems like python 3 doesn't allow for this syntax, returning: 但似乎python 3不允许这种语法,返回:

Argument 'x' was not of type < class 'A' >. 参数'x'不是<class'A'>类型。 Actual type was B. 实际类型是B.

Any help? 有帮助吗?

By default enforce applies invariant type checking. 默认情况下,enforce应用不变类型检查。 The type has to match directly - or an error is thrown. 类型必须直接匹配 - 否则会引发错误。

In order for an instance of a subclass to be accepted, the mode can be changed to covariant by adding : 为了接受子类的实例,可以通过添加以下内容将模式更改为协变:

enforce.config({'mode ': 'covariant'})

at a point in the code that is executed before any type checking is done (ie near the start). 在任何类型检查完成之前(即在开始附近)执行的代码中的某一点。

Other modes are available as described in the documentation. 其他模式可用,如文档中所述。

For further informations see : https://github.com/RussBaz/enforce 有关更多信息,请参阅: https//github.com/RussBaz/enforce

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

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