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

Python-导入模块获取全局变量

  •  1
  • ved  · 技术社区  · 7 年前

    import numpy
    zz = numpy
    
    class Something(object):
        def __init__(self):
            self.xp = zz
    

    和一个测试脚本。py:

    from testclass import Something
    x = Something()
    print(x.xp)
    

    Something (及其 __init__ zz . 因此,考虑到这个问题,我的问题是,当从模块导入时,Python是否“运行”了模块文件中的所有内容?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Blender    7 年前

    对执行时:

    from testclass import Something
    

    其作用与:

    import testclass
    Something = testclass.Something
    

    __all__ ). 对于极端情况,请考虑以下因素:

    a.py :

    import random
    
    if random.random() > 0.5:
        class Foo(object):
            pass
    else:
        class Bar(object):
            pass
    

    跑步 from a import Foo a 模块对象可能有也可能没有 Foo 属性