python导入嵌套类速记

Kev*_*lan 6 python import class

如何使用“as”速记导入嵌套包?

这个问题类似于在嵌套包中导入模块,只是嵌套在同一个 .py 文件中,而不是跨文件夹。

在 foo.py 中(所有 python 文件都在同一个包中,并且是 3.4 版):

class Foo:
    class Bar:
        ...
Run Code Online (Sandbox Code Playgroud)

我可以在另一个 .py 文件中访问这些子类:

from . import foo
...
bar = foo.Foo.Bar()
Run Code Online (Sandbox Code Playgroud)

我想做什么:

from . import foo.Foo.Bar as Bar  # DOES NOT WORK: "unresolved reference" error.
...
bar = Bar()  # saves typing.
bar2 = Bar()
...
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

Mar*_*ers 10

嵌套 Python 类没有什么意义;除了嵌套命名空间之外,这样做没有任何特殊意义。有很少任何这样做的必要。如果您需要生成额外的命名空间,只需使用模块即可。

您不能直接导入嵌套类;你只能导入模块全局变量,所以Foo在这种情况下。您必须导入最外层的类并创建一个新的引用:

from .foo import Foo
Bar = Foo.Bar
del Foo  # remove the imported Foo class again from this module globals
Run Code Online (Sandbox Code Playgroud)

del Foo完全是可选的。上面确实说明了为什么您不想从嵌套类开始。

  • 拥有内部类有一个要点:将代码上下文化。例如,属于某个接口的错误。您正在按结构记录代码。 (3认同)