Skip to main content
 首页 » 编程设计

python之IDE 推断 Python 类型

2025年05月04日21lexus

我正在用 Python 编写一个方法,它看起来像这样:

def rgb_to_grayscale(image): 
    print(image.shape) 
    pass 

此处预期的类型是 numpy.ndarray,它基本上是 OpenCV 中的图像。 IDE 怎么可能预先推断出此对象的类型,以便我在方法内部获得自动完成功能?

我正在使用 PyCharm。如果有人知道任何其他能够这样做的 IDE,我愿意接受建议。

请您参考如下方法:

自 Python 3.5 起,您可以使用 type hints :

def rgb_to_grayscale(image: numpy.ndarray): 

此外,Pycharm 能够通过 defining them in the docstring 识别类型.我更喜欢这个选项,因为它更清晰(在我看来)并且迫使你实际编写一个文档字符串 - 这对于生产代码(和一般而言)非常重要。你可以这样做:

def rgb_to_grayscale(image): 
    """ 
    :param numpy.ndarray image: the image to be printed 
    """ 
    print(image.shape) 

更多 Pycharm 可以检测类型的方法,在 this help link