Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

python: Two modules and classes with the same name under different packages

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

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()

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'

I'm not able to figure out why is it erroring out? The directories ShutterDeck, Helper and Controller have __init__.py in them.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want to import the User modules in the package __init__.py files to make them available as attributes.

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.

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...