python中的import关键字如何实际工作? [英] How does import keyword in python actually work?

查看:238
本文介绍了python中的import关键字如何实际工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有3个文件:

a.py

from d import d

class a:
    def type(self):
        return "a"
    def test(self):
        try:
            x = b()
        except:
            print "EXCEPT IN A"
            from b import b
            x = b()
        return x.type()

b.py

import sys

class b:
    def __init__(self):
        if "a" not in sys.modules:
            print "Importing a!"
            from a import a
        pass
    def type(self):
        return "b"
    def test(self):
        for modules in sys.modules:
            print modules
        x = a()
        return x.type()

c.py

from b import b
import sys

x = b()
print x.test()

并运行python c.py

and run python c.py

Python回来抱怨:

Python comes back complaining:


NameError:全局名称'a'不是
定义

NameError: global name 'a' is not defined

但是,sys.modules中的IS:

But, a IS in sys.modules:

copy_reg
sre_compile
locale
_sre
functools
encodings
site
__builtin__
operator
__main__
types
encodings.encodings
abc
errno
encodings.codecs
sre_constants
re
_abcoll
ntpath
_codecs
nt
_warnings
genericpath
stat
zipimport
encodings.__builtin__
warnings
UserDict
encodings.cp1252
sys
a
codecs
os.path
_functools
_locale
b
d
signal
linecache
encodings.aliases
exceptions
sre_parse
os

我可以改变b.py这样:

And I can alter b.py such that:

x = a()

更改为

x = sys.modules [a]。a()

x = a()
changes to
x = sys.modules["a"].a()

和python很乐意运行它。

And python will happily run that.

由此产生了几个问题:

为什么python说它没有'知道它是什么,当它在sys.modules中时?

使用sys.modules以正确的方式访问类和函数定义?

什么是正确的 导入模块的方法?

即来自模块导入的
x


导入模块

Why does python say it doesn't know what a is, when it is in sys.modules?
Is using sys.modules a "proper" way to access class and function definitions?
What is the "right" way to import modules?
ie from module import x
or
import module

推荐答案

我想这是一个范围问题,如果你在构造函数中导入一个模块,你只能在你的构造函数中使用它,之后import statement。

I guess it's a problem of scoping, if you import a module in your constructor you can only use it in your constructor, after the import statement.

这篇关于python中的import关键字如何实际工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆