【问题标题】:type hint for class type as argument类类型的类型提示作为参数
【发布时间】:2023-04-06 20:04:02
【问题描述】:

在 ros2 的 python 客户端库中,有一个函数接受类类型作为参数(不是该类的实例,而是定义)。

例如

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 类型提示,因为可以使用() 调用类类型来构造对象。但这并不能很好地传达它的真正含义。

def foo(class_type: Executable):
   obj: Any = class_type()

如果有类似的东西会更好:

def foo(class_type: Class):
   object: Any = class_type()

有这样的吗?执行此操作的标准方法是什么?

理想情况下,我希望它与 MyPy 静态类型检查系统一起使用。

【问题讨论】:

标签: python python-3.x mypy python-typing ros2


【解决方案1】:

实际上有一个你想要的类型提示,它只是称为Type 而不是Class,这里是它的文档:https://docs.python.org/3/library/typing.html#typing.Type

你也可以看到你可以告诉它它应该是一个类,所以在你给出的例子中它是:

Type[String]

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 2016-01-27
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多