我正在使用Python中的COM对象,使用win32com.client
中的Dispatch
来向第三方软件公开可编程接口。我的项目还利用了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
在上面的代码片段中,我会将'type_of_com_object_here'替换为COM对象类型。
我的第一个想法是在实例上调用
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
这个方法不能返回适合定义COM对象的类型。我认为可以使用TypeVar('T')
和Generic[]
创建一个抽象基类,但是我不确定是否有更好的Pythonic方法。
谢谢