我一直在学习python的一些动态'插件加载',并注意到import module
和from package import module
之间没有什么问题,而是一个有趣的区别。`import module`和`from package import module`之间的区别
我创建了由四个文件(就像我自己的设置为我想要达到的)
文件树看起来像这样一个测试脚本:
- 测试(主包)
- SUP(包,插件文件夹)
- __init__.py
- uber.py(插件)
- __init__.py
- bar.py('main'程序)
- foo.py(需要动态地增加功能对象)
- poo.py(装饰)
- SUP(包,插件文件夹)
poo.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目录'__init __。py' – vascop 2012-03-22 21:48:48
它们的存在。懒惰把它们放在那个List中。但特别为你我会添加它们。 – 2012-03-22 21:52:30
你说第一个不起作用是什么意思?如果你看到一个例外,请包括回溯。 – subdir 2012-03-22 22:33:43