小编Tom*_*ick的帖子

python 中 COM 对象的正确类型提示是什么?

我在 python 中使用 COM 对象来向 3rd 方软件公开可编程接口。这是通过使用Dispatchfrom来实现的win32com.client。我的项目也一直在使用 python.3.7 中的类型提示,但是我不确定如何为了类型提示的目的定义这些 COM 对象的类型。这个问题涉及我拥有的所有 COM 对象,一个真实的例子是 Microsoft Direct X Recordset: Dispatch("ADODB.Recordset")

from win32com.client import Dispatch
def create_my_com_object_instance(input_arg: Dict[str, Union[str, float, int]]) -> <type_of_com_object_here>:
    my_instance = Dispatch("ADODB.Recordset")
    # Set attributes/call methods of this instance here ... 
    return my_instance
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中,我将用 COM 对象类型替换“type_of_com_object_here”。

我的第一个想法是调用type()实例并使用返回的类型:

x = Dispatch("ADODB.Recordset")
x
Out[1]: <win32com.gen_py.Microsoft ActiveX Data Objects 6.1 Library._Recordset instance at 0x83848456>
type(x)
Out[2]: win32com.gen_py.B691E011-1797-432E-907A-4D8C69339129x0x6x1._Recordset._Recordset
x.__class__
Out[3]: win32com.gen_py.B691E011-1797-432E-907A-4D8C69339129x0x6x1._Recordset._Recordset
Run Code Online (Sandbox Code Playgroud)

这不会返回用于定义 COM 对象的合适类型。我相信我可以使用TypeVar('T')and创建一个抽象基类 …

python com type-hinting

5
推荐指数
1
解决办法
842
查看次数

标签 统计

com ×1

python ×1

type-hinting ×1