类内的python注释

2024-09-30 18:15:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在修补一些图算法,我想让自己成为一个通用的图/边框架。 我首先创建了一个Edge类:

class Edge:
    source = None
    destination = None
    isDirected = False
    isWeighted = False
    weight = None

    def __init__(self, source, destination, isDirected = False, weight = None):
        self.source = source
        self.destination = destination
        self.isDirected = isDirected
        if not weight is None:
            self.isWeighted = True
            self.weight = weight

    def isSameEdge(self, edge: {'help': 'Some helpfull text goes here', 'type': Edge}):
    if \
        self.isDirected != edge.isDirected or \
        self.isWeighted != self.isWeighted or \
        self.weight != edge.weight:
        return False
    if self.isDirected:
        if \
            self.destination != edge.destination or \
            self.source != edge.source:
            return False
    return True

我收到以下错误消息:

def isSameEdge(self, edge: {'help': 'Some helpfull text goes here', 'type': Edge}):
NameError: name 'Edge' is not defined

我的问题是:

1)如何通知python isSameEdge函数中的edge参数是edge类型

2)我不想限制类型,我只想让Pycharm/任何其他IDE给我提供关于可用于的方法/类变量的提示


Tags: orselfnonefalsesourcereturnifdef
1条回答
网友
1楼 · 发布于 2024-09-30 18:15:00

引用python.org:

Some tools may want to support type annotations in code that must be compatible with Python 2.7. For this purpose this PEP has a suggested (but not mandatory) extension where function annotations are placed in a # type: comment. Such a comment must be placed immediately following the function header (before the docstring).

有关详细信息,请查看此PEP

Python 3代码:

def embezzle(self, account: str, funds: int = 1000000, *fake_receipts: str) -> None:
    """Embezzle funds from account using fake receipts."""
    <code goes here>

与[python 2.7]等价,如下所示:

def embezzle(self, account, funds=1000000, *fake_receipts):
    # type: (str, int, *str) -> None
    """Embezzle funds from account using fake receipts."""
    <code goes here>

编辑:定义变量参数数据类型

您应该将其定义为Union[int, float, None]

相关问题 更多 >