Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python类中公开任意方法名称以供IDE读取_Python_Class_Interface_Members - Fatal编程技术网

在python类中公开任意方法名称以供IDE读取

在python类中公开任意方法名称以供IDE读取,python,class,interface,members,Python,Class,Interface,Members,情况是这样的。假设你 from nastymodule import NastyObject1, NastyObject2, NastyObject3 这个NastyObject的引擎盖下有一个奇怪的实现,由于接口(COM、dll调用等)错综复杂,它无法清晰地公开其方法,因此IDE无法建议它们。从文档中可以看到,NastyObject1有一个方法do\u thing,NastyObject2有一个方法do\u other\u thing,事实上 NO1 = NastyObject1() res

情况是这样的。假设你

from nastymodule import NastyObject1, NastyObject2, NastyObject3
这个
NastyObject
的引擎盖下有一个奇怪的实现,由于接口(COM、dll调用等)错综复杂,它无法清晰地公开其方法,因此IDE无法建议它们。从文档中可以看到,
NastyObject1
有一个方法
do\u thing
NastyObject2
有一个方法
do\u other\u thing
,事实上

NO1 = NastyObject1()
res = NO1.do_thing()
NO2 = NastyObject2()
res = NO2.do_other_thing()
完美地工作,如文件所述。唯一的问题是,正如我所说的,由于实现不明确,IDE不知道这个方法
do_thing
,或者该类的任何其他方法。现在,出于某些原因,我必须为所有
NastyObject
类编写一个唯一的
NstObjWrapper
类,能够动态公开这些方法

请记住,我已经编写了
NstObjWrapper
\uu getattr\uuu
,因此

NOW1 = NstObjWrapper('NastyObject1')
res = NOW1.do_thing()
NOW2 = NstObjWrapper('NastyObject2')
res = NOW2.do_other_thing()
已经工作了;我只需要找到一种方法来动态地使IDE(以及任何类型的类检查器)意识到
NOW1
有一个
do\u thing
方法,
NOW2
有一个
do\u other\u thing
方法

NstObjWrapper
如有必要,可通过详尽、硬编码的dict通知NastyObject的方法:

methods_dict = {'NastyObject1': ['do_thing', ......]
                'NastyObject2': ['do_other_thing', .......]
                'NastyObject3': [.......]}
但是,由于类必须能够包装所有对象,所有对象都有不同的方法,因此不能只定义具有相同名称的方法,然后调用包装的NastyObject的方法


这可能吗?你会怎么做?

解决这个问题的一个非常简单的方法是:

class my_class_func():
    def do_thing():
        pass
    def func2():
        pass
    def func3():
        pass
    def func4():
        pass
NOW1 = NstObjWrapper('NastyObject1') # type: my_class_func
res = NOW1.do_thing()
每个func对应于所需的一个func,然后告诉IDE您创建的类属于该特定类的类型,如下所示:

class my_class_func():
    def do_thing():
        pass
    def func2():
        pass
    def func3():
        pass
    def func4():
        pass
NOW1 = NstObjWrapper('NastyObject1') # type: my_class_func
res = NOW1.do_thing()
您将获得自动完成,因为我们编写“类型”注释的方式符合pep约定


无论哪种方式,我都不确定这是最好的方式。

您实际上没有定义任何内容,它只是帮助IDE自动完成。对象类型仍然是NstObjWrapper。