我可以在本地类中使用导入模块中的函数吗? (蟒蛇)

时间:2014-01-10 15:15:43

标签: python import module

我想实现类似下面的代码,但我得到了'全局名称import_module未定义'错误。是否可以在本地类中使用导入模块中的函数?如果有可能,它是如何完成的?


class local_class():
    def local_function():
        action = raw_input()
        if action = 'fow':
            import_module.import_function
        else:
            print 'null'

3 个答案:

答案 0 :(得分:1)

是的,这是完全可能的,但您需要导入模块。

class local_class():
    def local_function():
        action = raw_input()
        if action = 'fow':
            import import_module
            import_module.import_function
        else:
            print 'null'

答案 1 :(得分:0)

是。但你必须import模块:

class local_class():
    def local_function():
        action = raw_input()
        if action = 'fow':
            import import_module
            import_module.import_function
        else:
            print 'null'

假设import_module.pysys.path

中的有效模块

答案 2 :(得分:0)

您需要将import语句放在所需范围内的某处:

import import_module
class local_class():
    def local_function():
        action = raw_input()
        if action = 'fow':
            import_module.import_function
        else:
            print 'null'

class local_class():
    def local_function():
        import import_module
        action = raw_input()
        if action = 'fow':
            import_module.import_function
        else:
            print 'null'
# import_module.import_function would fail here, import_module is local
# to local_class.local_function
# BUT...

但要注意,一旦导入,模块将由python内部存储,因此即使您无法在另一个范围内访问它,如果再次导入模块,您将获得相同的实例。例如:

>>> def func():
    import shutil
    # Store a new attribute in the module object
    shutil.test = 5
    print(shutil.test)


>>> func()
5
>>> shutil.test
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    shutil.test
NameError: name 'shutil' is not defined
>>> import shutil
>>> shutil.test # The attribute exists because we get the same module object
5
>>> 
>>> ================================ RESTART ================================
>>> shutil.test
Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    shutil.test
NameError: name 'shutil' is not defined
>>> import shutil
>>> shutil.test
Traceback (most recent call last):
  File "<pyshell#50>", line 1, in <module>
    shutil.test
AttributeError: 'module' object has no attribute 'test'
>>>