我怎样才能告诉PyCharm参数期望是什么类型?
|
当涉及到构造函数,赋值和方法调用时,PyCharm IDE非常擅长分析我的源代码并弄清楚每个变量应该是什么类型。我很喜欢它,因为它给了我很好的代码完成和参数信息,并且如果我尝试访问一个不存在的属性,它会给我警告。
但是当涉及到参数时,它一无所知。代码完成下拉列表无法显示任何内容,因为它们不知道参数的类型。代码分析无法查找警告。
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指出,因此它可以在其代码完成下拉列表中向我展示all2ѭ的所有属性,并突出显示警告(如果我调用了错误的方法),依此类推。
有没有办法给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.
相关部分是文档字符串的“ 4”行。
如果您还转到文件>设置> Python集成工具,并将\“ Docstring格式\”设置为\“ Epytext \”,则PyCharm \的视图>快速文档查找将漂亮地打印参数信息,而不仅仅是打印所有@-行原样。
没有找到相关结果
已邀请:
5 个回复
殿虫
朗排谎纷瘟
有时,这对于不需要文档字符串的非公共方法很有用。另外一个好处是,这些注释可以通过代码访问:
更新:从PEP 484(已为Python 3.5接受)开始,使用注释指定参数和返回类型也是官方约定。
苛肠倒俱
相关部分是文档字符串的“ 4”行。 我的目的不是要从CrazyCoder或原始提问者那里窃取分数,而应尽其所能。我只是以为简单的答案应该在\'answer \'插槽中。
橙绥
参见:https://www.jetbrains.com/help/pycharm/2016.1/type-hinting-in-pycharm.html#legacy
公藕