首页 > 解决方案 > Python - 使用类型提示时出现 NameError

问题描述

我可以Unresolved reference 'Segment'在 pycharm 中看到,但在视频中作者和我有相同的代码,作者似乎没有任何错误。

如果我尝试运行它,我会收到以下错误:

C:\Users\Username\anaconda3\python.exe G:/Temp/Python/advanced-oop/flight.py
Traceback (most recent call last):
  File "G:/Temp/Python/advanced-oop/flight.py", line 4, in <module>
    class Flight:
  File "G:/Temp/Python/advanced-oop/flight.py", line 5, in Flight
    def __init__(self, segments: List[Segment]):
NameError: name 'Segment' is not defined

Process finished with exit code 1

这是完整的代码:

from typing import List


class Flight:
    def __init__(self, segments: List[Segment]):
        self.segments = segments

    @property
    def departure_point(self) -> str:
        return self.segments[0].departure


class Segment:
    def __init__(self, departure, destination):
        self.departure = departure
        self.destination = destination


flight = Flight([Segment('GLA', 'LHR')])
print(flight.departure_point)

这是视频的屏幕截图,它执行得很好。

在此处输入图像描述

标签: python

解决方案


def __init__(self, segments: List[Segment]):Python 解释该行时,该类Segment尚未定义。交换 和 的定义,Flight代码Segment应该可以工作。


推荐阅读