python:不同包下同名的两个模块和类

2022-01-13 00:00:00 python python-3.x package python-import

问题描述

我已经开始学习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'

我无法弄清楚为什么会出错?ShutterDeckHelperController 目录中有 __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_.pyController/__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()

相关文章