[英]How to write the type hint for an argument that can be of either class A or class B?
[英]type hint for class type as argument
在 ros2 的 python 客户端库中有一个 function 接受 class 类型作为参数(不是 class 的实例,而是定义)。
例如
from std_msgs.msg import String
#String is python class i.e,
#class String:
# ...
class MyNode(Node)
def __init__(self):
super().__init__('my_node')
self.add_subscription(String, 'chatter', lambda msg : print(msg))
#Note that we pass in the type String, not an object, i.e String()
如何使用 python 类型注释来注释这样的东西?
一种方法是使用Executable
类型提示,因为可以使用()
调用 class 类型来构造 object。但这并不能很好地表达它的真实含义。
def foo(class_type: Executable):
obj: Any = class_type()
如果有这样的东西会更好:
def foo(class_type: Class):
object: Any = class_type()
有这样的东西吗? 这样做的标准方法是什么?
理想情况下,我希望它能与 MyPy static 类型检查系统一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.