當談到構造函數,賦值和方法調用時,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