2

名前空間をたとえばsandbox.auto.toolsからsandbox.toolsに短縮したいと思います 。どうすればそれを達成できますか(自動は冗長です)?他のメッセージを調べましたが、探しているものに似たものは実際には見つかりませんでした。以下は私のディレクトリ構造です。

sandbox\auto\tools\foo.py (contains a function display() as described below)
    def display():
        print "hello"

sandbox\test\bar.py 
    import sandbox.auto.tools as sandbox.tools (Error)

私は次のことができることを知っています。

  sandboox\test\bar.py 
    from sandbox.auto.tools import foo as tools
    tools.display()

提案/ポインタはありますか?

4

4 に答える 4

3

指定した正確な構文を (sandbox.toolsの代わりに使用してsandbox_tools) 許可するには、モジュールをインポートする前または後にモジュールを変更する必要があります。

安い方法:

import sandbox.auto.tools
sandbox.tools = sandbox.auto.tools

永続的な方法 (モジュール ソースを変更する機能が必要です):

sandbox/__init__.pyソースを作成または変更して、次のように記述します。

import auto.tools as tools
__all__ = ['tools', ...]
于 2012-06-21T16:57:16.607 に答える
0

私は最終的にあなたの提案/ヘルプで解決策を見つけました. しかし、私はまだそれに満足していません。

サンドボックス/ init .py

import auto.tools as tools
__all__ = ['tools']

import sandbox.auto.tools.foo
sandbox.tools.foo = sandbox.auto.tools.foo

sandbox/test/bar.py - これは機能しているようです

import sandbox
print dir(sandbox)
foo = sandbox.tools.foo
foo.display()

だけど――もうこんなことは言えない

from sandbox.tools import foo
or
from sandbox.tools import foo as tools2

参照へのハンドルを取得できるように見えますが、まだ Python の名前空間の概念を完全には理解していません。

于 2012-06-22T12:42:37.090 に答える
0

私の同僚の 1 人が、sandbox/ init.pyに次の行を追加すれば、この特定の問題を解決できるはずだと指摘しました。

パス.append('sandbox/auto')

于 2012-06-27T20:25:32.530 に答える
0

あなたが本当にsandbox.tools利用可能になりたい場合は、これをに追加してsandbox/__init__.pyください:

from .auto import tools

toolsこれにより、パッケージの名前空間が追加され、次のsandboxことが可能になります。

from sandbox import tools
tools.dispaly()

または、あなたが求めたものは次のとおりです。

import sandbox
sandbox.tools.display()
于 2012-06-21T16:56:01.663 に答える