gpt4 book ai didi

python - `import module` 和 `from package import module` 之间的差异

转载 作者:太空狗 更新时间:2023-10-30 03:06:02 25 4
gpt4 key购买 nike

我一直在学习 python 的一些动态“插件加载”,并注意到 import modulefrom package import module 之间的一个不是真正的问题而是一个有趣的区别.

我创建了一个由四个文件组成的测试脚本(类似于我自己的设置以实现我想要实现的目标)

文件树如下所示:

  • 测试(主包)
    • sup(包,插件文件夹)
      • __初始化__.py
      • uber.py(插件)
    • __初始化__.py
    • bar.py('主程序')
    • foo.py(需要动态添加功能的对象)
    • poo.py(装饰器)

便便.py:

from test import foo

def decorate(method):
print "before:", method.__name__ in dir(foo.Foo)
setattr(foo.Foo, method.__name__, method)
print "after :", method.__name__ in dir(foo.Foo)
return method

foo.py:

import os

class Foo(object):

def __init__(self):
self.__loadplugins("sup")

@classmethod
def __loadplugins(cls, plugindir):
for f in os.listdir(os.path.join(os.path.dirname(__file__), plugindir)):
if f.endswith(".py"):
__import__(("%s.%s" % (plugindir, f))[0:-3])

uber.py:

from test import poo

@poo.decorate
def aFunction(self, anArg):
print anArg

我有两个版本的 bar.py,这个不行:

import foo

f = foo.Foo()

f.aFunction("print goes here") # pylint: disable-msg=E1101

这个确实有效:

from test import foo

f = foo.Foo()

f.aFunction("print goes here") # pylint: disable-msg=E1101

这两个栏的唯一区别是导入。一个是相对的,另一个不是。但是相对的不行,绝对的才行。有没有人可以在他的机器上复制这个并且可以对它发生的原因给出某种解释?

更新
认为也注意我的 python 版本会很有用:使用普通的 python 版本 2.7.2 x86

更新
“错误”bar.py 的输出:

before: False
after : True
Traceback (most recent call last):
File "C:\Users\Daan\workspace\python\mytests\src\test\bar.py", line 6, in <module>
f.aFunction("print goes here") # pylint: disable-msg=E1101
AttributeError: 'Foo' object has no attribute 'aFunction'

“正确”bar.py 的输出:

before: False
after : True
print goes here

最佳答案

我假设您在“test”目录中并且具有环境变量 PYTHONPATH=..(因此您可以执行“import foo”和“from test import foo”)。

在这种情况下,foo 和 test.foo 是两个不同的模块,分别加载(尽管它们是从同一个文件加载的)。

test.poo 模块中的'decorate' 函数将方法添加到 test.foo 中的类 'Foo'(poo.py 的第一行:“from test import foo”),同时 'Foo' 类来自foo 模块保持不变。

关于python - `import module` 和 `from package import module` 之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9831031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com