python:不同包装下名称相同的两个模块和类 [英] python: Two modules and classes with the same name under different packages
问题描述
我已经开始学习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
中都添加:
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:不同包装下名称相同的两个模块和类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!