問題描述
我已經開始學習python并編寫一個練習應用程序.目錄結構看起來像
I have started to learn python and writing a practice app. The directory structure looks like
src
|
--ShutterDeck
|
--Helper
|
--User.py -> class User
--Controller
|
--User.py -> class User
src
目錄位于 PYTHONPATH
中.在另一個文件中,比如說 main.py
,我想訪問兩個 User
類.我該怎么做.
The src
directory is in PYTHONPATH
. In a different file, lets say main.py
, I want to access both User
classes. How can I do it.
我嘗試使用以下方法,但失敗了:
I tried using the following but it fails:
import cherrypy
from ShutterDeck.Controller import User
from ShutterDeck.Helper import User
class Root:
@cherrypy.expose
def index(self):
return 'Hello World'
u1=User.User()
u2=User.User()
這肯定是模棱兩可的.我能想到的另一種(c++ 實現方式)方式是
That's certainly ambiguous. The other (c++ way of doing it) way that I can think of is
import cherrypy
from ShutterDeck import Controller
from ShutterDeck import Helper
class Root:
@cherrypy.expose
def index(self):
return 'Hello World'
u1=Controller.User.User()
u2=Helper.User.User()
但是當上面的腳本運行時,它給出了以下錯誤
But when above script is run, it gives the following error
u1=Controller.User.User()
AttributeError: 'module' object has no attribute 'User'
我無法弄清楚為什么會出錯?ShutterDeck
、Helper
和 Controller
目錄中有 __init__.py
.
I'm not able to figure out why is it erroring out? The directories ShutterDeck
, Helper
and Controller
have __init__.py
in them.
推薦答案
您要導入包 __init__.py
文件中的 User
模塊,使其可用作屬性.
You want to import the User
modules in the package __init__.py
files to make them available as attributes.
所以在 Helper/__init_.py
和 Controller/__init__.py
中添加:
So in both Helper/__init_.py
and Controller/__init__.py
add:
from . import User
這使模塊成為包的屬性,您現在可以這樣引用它.
This makes the module an attribute of the package and you can now refer to it as such.
或者,您必須自己完整導入模塊:
Alternatively, you'd have to import the modules themselves in full:
import ShutterDeck.Controller.User
import ShutterDeck.Helper.User
u1=ShutterDeck.Controller.User.User()
u2=ShutterDeck.Helper.User.User()
所以用他們的全名來稱呼他們.
so refer to them with their full names.
另一種選擇是使用 as
重命名導入的名稱:
Another option is to rename the imported name with as
:
from ShutterDeck.Controller import User as ControllerUser
from ShutterDeck.Helper import User as HelperUser
u1 = ControllerUser.User()
u2 = HelperUser.User()
這篇關于python:不同包下同名的兩個模塊和類的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!