【发布时间】:2021-08-28 11:39:39
【问题描述】:
编辑:这个问题是假设我可以在不导入整个模块的情况下导入部分模块。事实证明情况并非如此,所以我决定还是用from ex45_extras import * 导入整个模块。这使得这个问题毫无意义,但我决定不删除这个问题,以便其他有相同问题的初学者可以来到这里并找出可悲的事实:你不能将模块作为部件导入
以下是原题:
我是初学者,所以对于菜鸟问题很抱歉。我想从带有变量的模块中调用特定的类。我不想调用整个模块。我需要使用这个类 Nav() 来控制正在导入的类。有没有办法做到这一点?还是有更好的解决方案?
class Nav():
def __init__(self):
print("This is class Nav")
def play(self):
current_scene_name = "A()" # this is where the variable is defined
from ex45_extras import current_scene_name # <- this is the one
x = Nav()
x.play()
目前它正在引发此错误:
This is class Nav
Traceback (most recent call last):
File "D:\Programming\Python\LPTHW_Exs\ex45\test.py", line 11, in <module>
x.play()
File "D:\Programming\Python\LPTHW_Exs\ex45\test.py", line 7, in play
from ex45_extras import current_scene_name
ImportError: cannot import name 'current_scene_name' from 'ex45_extras' (D:\Programming\Python\LPTHW_Exs\ex45\ex45_extras.py)
【问题讨论】:
-
请使用完整的错误回溯更新您的问题。
-
您可以在函数中本地导入模块并使用“getattr”来检索包含的类或函数(它们是模块的属性)。
-
@MichaelButscher 和通常的方式预先导入模块不一样吗?
-
@quamrana k 我现在做到了
-
ex45_extras似乎有问题。你期望current_scene_name是什么?
标签: python import python-import