[英]How can I retrieve the docstring for a property of a Python class instance?
[英]Python docstring type annotation — a class, not an instance?
假設我有:
class A(object):
pass
class B(A):
pass
我想聲明一個將 A 的子類作為參數的函數:
def do_something(klass):
"""
:type klass: WHAT_HERE
"""
pass
我應該在 WHAT_HERE 中放什么? 如果我這樣做:
:type klass: A
PyCharm 認為我應該給出一個 A 的實例作為參數,而不是類本身。
根據pycharm 文檔,您可以獲得的最接近的是:
() -> SomeClass
所以在你的例子中
def do_something(klass):
"""
:type klass: () -> A
"""
pass
這意味着(對於 PyCharm)您提供的參數是一個返回給定類型對象的函數。 它會在對象創建后正確鍵入提示任何內容。
Guido 在這里回答了這個問題,但我相信 PyCharm 沒有正確支持 Python 2 中的適當語法。我相信語法應該是(...) -> A
in PyCharm with Python 2。在 Python 3 中,適當的語法是Callable[..., A]
。
我注意到 PyCharm 也不將() -> A
視為一個類; 如果您使用此語法在 A 上調用類方法,PyCharm 檢查將標記它無法找到引用的類方法。
這已在 JetBrains bugtracker 中歸檔,但根據之前的評論已關閉。 鑒於 Guido 最近在第一篇參考文獻中的評論,我希望 JetBrains 能夠重新開放。
答案是Type
。 如果你安裝了一個typing
模塊,你還可以將這個類綁定為某個東西的子類,如下例所示:
class BaseUser(): pass
class Admin(BaseUser): pass
class Staff(BaseUser): pass
class Client(BaseUser): pass
然后
from typing import Type, TypeVar
U = TypeVar('U', bound=BaseUser)
def new_user(user_class):
"""
type user_class: Type[U]
"""
return user_class()
以下是用法
new_user(Admin)
new_user(Client)
new_user(Staff)
皮查姆 | IDEA 對typing
提示的理解非常好,所以它會做到這一點
所有類都是type
類的實例:
>>> class Foo:
... pass
...
>>> type(Foo())
<class '__main__.Foo'>
>>> type(Foo)
<class 'type'>
>>> type(Foo) is type
True
所以,一個有效的答案是:
:type klass: type
在 PyCharm 或 IDEA 中使用 Python 2 的文檔字符串語法無法做到這一點。
但是,您可以通過在用法上方放置assert
語句來獲得變量的代碼完成:
def call_foo(cls):
"""
Calls the class method ``foo`` of the given class.
:param cls: a subclass of SomeClass
:type cls: type
"""
assert issubclass(cls, SomeClass)
cls.foo() # you'll get code completion here for the foo method defined in SomeClass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.