问题描述
假设有一组类 Map1,Map2,Map3,... 都是从 BaseMap 扩展而来的,我使用一些反射机制来获取子 Map 的实例.我想动态获取这些类之一的实例并将其存储在变量 m
中,并让 pydev 将该类型识别为 BaseMap,以便我可以在其上使用单词补全.
Suppose there's a set of class Map1,Map2,Map3,... all extended from BaseMap, and I use some reflection mechanism to get the child Map's instance. I want to dynamically get an instance of one of these classes and store it in a variable m
, and have pydev recognize the type as BaseMap so I can use word completion on it.
我发现一种解决方案是添加代码
I found one solution is to add the code
if False:
m = BaseMap(0,0,0)
在分配 m
之后和使用它之前.if 条件中的那行永远不会被执行,但它声明 m
是一个 BaseMap 类型对象.
after assigning m
and before using it. The line inside the if condition would never be executed, but it declares m
is a BaseMap type object.
这可能看起来很傻,但确实有效.还有其他方法吗?
This may look silly, but it did work. Is there any other way to do it?
推荐答案
您可以使用 assert isinstance(...)
在 pydev 中对变量进行自动完成,否则 pydev 将无法猜测正确的类型.
You can use assert isinstance(...)
to get autocompletion in pydev on variables where otherwise pydev would not be able to guess the correct type.
说你的代码是:
m = getAttr(someThing, 'someAttr')
m.*no autocompletion*
pydev 无法知道 m
的类型,因此不会显示自动完成.
pydev would not be able to know the type of m
and therefore won't show the autocompletion.
试试:
m = getAttr(someThing, 'someAttr')
assert isinstance(m, BaseMap) # or whatever class it is
m.*pydev shows autocompletion*
这有点hacky,但它会起作用(而且不会造成伤害).
It's somewhat hacky, but it will work (and also does not hurt).
这篇关于如何在pydev中声明变量的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!