简体   繁体   中英

Can I use a function from an import module inside a local class? (Python)

I want to realize a code like below, but I got a 'global name import_module is not defined' error. Is it possible to use a function from a imported module inside a local class? If it's possible, how is it done?


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

Yes, this is perfectly possible, but you need to import the module.

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

Yes. But you do have to import the module:

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

Assuming import_module.py was a valid module in sys.path

You need to place your import statement somewhere in the needed scope:

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

or

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...

But beware, once imported, the module will be stored internally by python, so that even if you can't access it in another scope, if you import the module again, you will get the same instance. For example:

>>> 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'
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM