Pyreverse:如何在生成 uml 报告时为方法和属性添加 return 类型?

Pyreverse: how to add return types for methods and properties when generating uml reports?

我正在使用 pyreversegraphviz 从 Python 模块成功生成 UML 报告。我可以看到 pylint 足够聪明,可以为某些属性说明输出数据类型是什么,但不是所有属性和 none 用于方法。

源代码:

def get_int():
    return 555

def get_math_int():
    return math.pow(2, 5)

class ClassFoo(object):
    def __init__(self, x, y):
        self.attr1 = "hello"
        self.attr2 = get_int()
        self.attr3 = get_math_int()

    def spam(self):
        return 77

class ClassBar(object):
    def __init__(self, x, y):
        self.attr4 = "hello"

    def spam(self):
        return 99

输出pdf

我已经调查了 pylint docstyle checker,但它看起来与我的问题无关。

是否可以通过注释、文档字符串或其他方式使用类型提示明确指定每个方法和属性将返回什么数据类型,以便它们显示在 pdf 报告中?

在 Python 3.5 或更高版本中,您可以使用内置的 typings module; in Python 2 or older versions of Python 3, mypy 是您唯一的选择。一个好的 IDE(例如 PyCharm)实际上会告诉你如果你犯了错误,如果你所有的 类 都有很好的注释。

提取类型信息非常痛苦,但首先要读取 类 上具有类型提示的 __annotations__ 属性(参见 PEP-0484)。

您的示例,完全使用 Python 3.5 或更高版本进行类型提示:

from typing import Any

def get_int() -> int:
    return 555

def get_math_int() -> int:
    return math.pow(2, 5)

class ClassFoo(object):
    def __init__(self, x: Any, y: Any):
        self.attr1 = "hello"
        self.attr2 = get_int()
        self.attr3 = get_math_int()

    def spam(self) -> int:
        return 77

class ClassBar(object):
    def __init__(self, x: Any, y: Any):
        self.attr4 = "hello"

    def spam(self) -> int:
        return 99