当谈到构造函数,赋值和方法调用时,PyCharm IDE非常擅长分析我的源代码并确定每个变量应该是什么类型。我喜欢它,因为它给了我很好的代码完成和参数信息,并且如果我尝试访问不存在的属性,它会给我警告。我该如何告诉PyCharm参数预期是什么类型?
但是当涉及到参数时,它什么都不知道。代码完成下拉菜单不能显示任何内容,因为它们不知道参数的类型。代码分析不能查找警告。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
peasant = Person("Dennis", 37)
# PyCharm knows that the "peasant" variable is of type Person
peasant.dig_filth() # shows warning -- Person doesn't have a dig_filth method
class King:
def repress(self, peasant):
# PyCharm has no idea what type the "peasant" parameter should be
peasant.knock_over() # no warning even though knock_over doesn't exist
King().repress(peasant)
# Even if I call the method once with a Person instance, PyCharm doesn't
# consider that to mean that the "peasant" parameter should always be a Person
这使得一定的含义。其他呼叫站点可以为该参数传递任何内容。但是如果我的方法需要一个参数类型,例如pygame.Surface
,我希望能够以某种方式向PyCharm表明,因此它可以在代码完成下拉列表中显示Surface
的所有属性,并突出显示警告如果我打电话错误的方法,等等。
有没有办法给PyCharm一个提示,并说“psst,这个参数应该是X型”? (或者,在动态语言的精神“这个参数应该呱呱像X”,我会罚款吗?)。
编辑: CrazyCoder的答案,下面,请问招。对于谁想要快速摘要像我这样的新人任何,那就是:
class King:
def repress(self, peasant):
"""
Exploit the workers by hanging on to outdated imperialist dogma which
perpetuates the economic and social differences in our society.
@type peasant: Person
@param peasant: Person to repress.
"""
peasant.knock_over() # Shows a warning. And there was much rejoicing.
相关部分是@type peasant: Person
行的文档字符串中。
如果您还要转到文件>设置> Python集成工具并将“文档字符串格式”设置为“Epytext”,则PyCharm的视图>快速文档查找将漂亮地打印参数信息,而不是仅打印所有@ -lines原样。
这是要注意的是reStructuredText的评论只使用有不同的写法相同的标签:'@参数XX:yyy'成为':PARAM XX: yyy'。请参阅http://www.jetbrains.com/pycharm/webhelp/creating-documentation-comments.html – Wernight 2012-04-22 23:13:17
为什么我们不能指定完全限定的类名? – aitchnyu 2014-12-31 09:35:07