Pyreverse:生成UML报告时如何为方法和属性添加返回类型?

时间:2019-01-22 23:03:21

标签: python uml graphviz pylint pygraphviz

我已成功使用pyreversegraphviz从Python模块生成UML报告。我可以看到pylint足够聪明,可以说某些属性是什么输出数据类型,而不是全部,方法也没有。

源代码:

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

enter image description here

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

是否可以通过注释,docstring或其他方式使用类型提示来明确指定每个方法和属性将返回哪种数据类型,以便将它们显示在pdf报告中?

1 个答案:

答案 0 :(得分:2)

在Python 3.5或更高版本中,您可以使用内置的typings module;在Python 2或更旧版本的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