python - 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)
这是视频的屏幕截图,它执行得很好。
解决方案
当def __init__(self, segments: List[Segment]):
Python 解释该行时,该类Segment
尚未定义。交换 和 的定义,Flight
代码Segment
应该可以工作。
推荐阅读
- threadpool - C#如何加速ThreadPool.QueueUserWorkItem?
- php - 表单数据未发送到 SQL 数据库
- c# - .NET 5 HttpClient 异常:无法建立 SSL 连接,内部:从传输流接收到意外的 EOF 或 0 字节
- seaborn - 如何删除seaborn热图中的颜色条?
- json - Postgres:计算 jsonb 中特定键的行数
- css - 为什么 CSS 文件在 readthedocs 中不起作用?
- algorithm - 计算一个项目可以分配到多个类别时的百分比
- javascript - 如何在字符串中的每个逗号后添加一个空格?
- http-live-streaming - 在没有 Jibri 和 Docker Lib Jitsi-meet 的情况下,有没有办法从 Jitsi Meet 直播到 youtube 或 facebook?
- azure - 使用文件流压缩文件并上传到 Azure Blobstorage