我惊喜地发现带有 PyDev 的 Eclipse 能够猜测大多数变量的类型并帮助显示成员列表。我正在学习 Python,我认为我应该忘记强类型语言的所有优点,但看起来我错了。
我想知道 IDE(甚至 Python 解释器)能走多远。我在下面的代码片段中定义了一些模块级变量,我希望 IDE 知道它们的类型。
关于 IDE 的问题 1:是否可以声明变量的类型以便代码补全了解其成员?
关于 Python 的问题 2:是否可以声明变量的类型,以便在执行过程中如果类型发生变化,我会收到警告?
例如,将光标放在以下代码段的第一个 c. 之后,然后按 ctrl+space,第一个建议是 val。耶!
Python 变量是动态的,它们的类型可以改变,这个技巧对第二个 c. 不起作用,因为 Eclipse 无法知道 c > 在模块级别定义并在 func2 中使用的将在 func1 中定义。
c = None
class MyClass:
val = 0
def func1():
c = MyClass()
print c. # Eclipse knows that val is a member of c
def func2():
print c. # Eclipse doesn't know that val is a member of c
请您参考如下方法:
def something(c):
#eclipse does not know what c is
assert isinstance(c,MyClass)
#now eclipse knows that c is an instance of MyClass
c. #autocomplete
