Python 文档字符串类型注释——一个类,而不是一个实例? [英] Python docstring type annotation -- a class, not an instance?

查看:65
本文介绍了Python 文档字符串类型注释——一个类,而不是一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有:

class A(object):
   pass

class B(A):
   pass

我想声明一个将 A 的子类作为参数的函数:

I want to declare a function that takes a subclass of A as an argument:

def do_something(klass):
   """
   :type klass: WHAT_HERE
   """
   pass

我应该在 WHAT_HERE 中放什么?如果我这样做:

What should I put in WHAT_HERE? If I make this:

:type klass: A

PyCharm 认为我应该给出一个 A 的实例作为参数,而不是类本身.

PyCharm thinks that I should give an instance of A as an argument, not the class itself.

推荐答案

根据 pycharm 文档 尽可能接近:

() -> SomeClass

所以在你的例子中

def do_something(klass):
   """
   :type klass: () -> A
   """
   pass

这意味着(对于 PyCharm)您提供的参数是一个返回给定类型对象的函数.它会在对象创建后正确键入提示.

This means (for PyCharm) that the argument you are providing is a function that returns an object of a given type. It will properly type hint anything after the object creation.

这篇关于Python 文档字符串类型注释——一个类,而不是一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆