我一直在學習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