【问题标题】:Importing a class by referring to it with a variable?通过使用变量引用类来导入类?
【发布时间】: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


【解决方案1】:

类名没有尾随 () 后缀 - 这就是您创建类名实例的方式(即通过调用它)。

无论如何,如果ex45_extras.py 定义了一个名为A 的类:

class A:
    pass

然后您可以通过包含其名称的字符串import该类,然后创建它的实例,如下所示:

class Nav():
    def __init__(self):
        print("This is class Nav")

    def play(self):
        import ex45_extras

        current_scene_name = 'A' # this is where the variable is defined
        class_ = getattr(ex45_extras, current_scene_name)  # Get class.
        instance = class_()  # Create instance of class.
        print(f'{instance=}')  # -> instance=<ex45_extras.A object at 0x010D4838>


x = Nav()
x.play()

【讨论】:

  • 看起来 Python 无论如何都会导入整个模块,所以我想我会接受这个。谢谢
  • 我知道没有办法不import 整个模块,因为这涉及到执行整个事情。您真正可以控制的只是其内容在您自己的代码范围内的可见性。在我的回答中,模块名称、类名称和实例名称都是 play() 函数中的局部变量,在它之外无法访问。
【解决方案2】:

猜这是因为您尝试导入字符串 "A()" 而不是类 A()

【讨论】:

  • 我不知道这是否是一个问题,但无论如何它并没有调查,它把变量名当作要导入的类的名称
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 2018-04-06
  • 2019-04-29
  • 2013-08-09
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
相关资源
最近更新 更多