代码之家  ›  专栏  ›  技术社区  ›  IanSR

在Python模块中访问别名函数

  •  2
  • IanSR  · 技术社区  · 16 年前

    pyscript.py:
    from shell import *
    basename("/path/to/file.ext")
    

    以及shell.py 模块包含:

    shell.py:
    from os.path import basename
    

    问题是导入到shell模块的函数不可用,因为import语句只包含函数、类和全局变量 在“shell”模块中,不是导入的。

    有什么办法可以解决这个问题吗?

    2 回复  |  直到 15 年前
        1
  •  3
  •   Mark Ransom    16 年前

    from shell import * 
    basename("/path/to/file.ext")
    

    外壳.py:

    from os.path import basename
    
        2
  •  2
  •   leoluk    16 年前

    这不是一个bug,而是一个特性:-)

    如果将m1导入一个模块m2,然后将m2导入另一个模块,那么它只会从m2导入内容,而不会从m1导入内容。这是为了防止污染。

    你可以这样做:

    外壳.py:

    import os.path
    basename = os.path.basename
    

    然后,在pyscript.py文件,您可以这样做:

    from shell import * # warning: bad style!
    basename(...)