简体   繁体   English

如何在pydev中声明变量的类型?

[英]how to declare variable's type in pydev?

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. 假设有一组Map1,Map2,Map3,...都是从BaseMap扩展的,并且我使用了一些反射机制来获取子Map的实例。 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. 我想动态获取这些类之一的实例并将其存储在变量m ,并让pydev将类型识别为BaseMap,以便可以在其上使用单词完成功能。

I found one solution is to add the code 我发现一种解决方案是添加代码

if False:
    m = BaseMap(0,0,0)

after assigning m and before using it. 在分配m和使用它之前。 The line inside the if condition would never be executed, but it declares m is a BaseMap type object. if条件内的行将永远不会执行,但它声明m是BaseMap类型的对象。

This may look silly, but it did work. 这可能看起来很傻,但是确实有效。 Is there any other way to do it? 还有其他方法吗?

You can use assert isinstance(...) to get autocompletion in pydev on variables where otherwise pydev would not be able to guess the correct type. 您可以使用assert isinstance(...)在pydev中的变量上获取自动补全功能,否则pydev无法猜测正确的类型。

Say your code is: 说你的代码是:

m = getAttr(someThing, 'someAttr')
m.*no autocompletion*

pydev would not be able to know the type of m and therefore won't show the autocompletion. pydev无法知道m的类型,因此不会显示自动补全。

Try: 尝试:

m = getAttr(someThing, 'someAttr')
assert isinstance(m, BaseMap) # or whatever class it is
m.*pydev shows autocompletion*

It's somewhat hacky , but it will work (and also does not hurt). 它有点hacky ,但是可以工作(也不会造成伤害)。

This question is similar to this post: Eclipse pydev auto-suggestions don't work in some cases 这个问题类似于这篇文章: Eclipse pydev自动建议在某些情况下不起作用

One good answer is already suggested (using asserts). 已经提出了一个很好的答案(使用断言)。 Another solution is to use a constructors as described in this link . 另一个解决方案是使用此链接中描述的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM