如何直接导入 Python 中的嵌套项?

How to directly import nested item in Python?

假设我有一个包含 Player.py 文件的 src 文件夹,其中包含 class PlayVideo。我可以直接从与 src 位于同一文件夹中的 main.py 文件导入 class 吗?

通常,要使用那个 class 我会做

from src import Player
    
Player.PlayVideo("videofile.mp4")

是否可以直接导入 PlayVideo class?

是的,只要 Player 是 Python 文件(.py)或 Python 模块(包含 __init__.py 文件的目录),您可以做:

from src.Player import PlayVideo

在此处查看有关导入子模块的文档:https://docs.python.org/3/tutorial/modules.html#packages

import matplotlib.pyplot as plt 

前一个是极其常见的导入。我猜你的答案是:

import src.Player.PlayVideo as PlayVideo

它适用于类似的东西:

import statsmodels.regression.linear_model as line

希望对您有所帮助!