1

I have been trying to fix this for a bit, and I must be missing something basic here (forgive me, I am relatively new to Python development):

I have a package structure like this:

base
|
 -->util
    __init__.py
    Class1.py
    Class2.py
__init__.py
Main.py

My classes are fairly benign:

class Class1(object):

    def __init__(self):

    # some methods...


class Class2(object):

    def __init__(self):

    # more methods...

In the Main.py, I have:

import utils

if __name__ == '__main__':
    c1 = utils.Class1()
    c2 = utils.Class2()

My PYTHONPATH is setup to include src, src\base, and src\base\utils. But, Python gives me this error when trying to run Main.py:

AttributeError: 'module' object has no attribute 'Class1'

Has someone encountered this, and do you know how to fix it? Thanks!

1
  • Do not name files as the classes inside. Thats a bad habbit as you don't know if sth is a class or a package. Use lowercase-only names for modules (files). Commented Feb 29, 2012 at 22:57

2 Answers 2

5

This is a little different than Java. In java each file is usually a class, in python, each file is a module. Given the scenario you describe here, you would do:

import utils.Class1
import utils.Class2

if __name__ == '__main__':
    c1 = utils.Class1.Class1()
    c2 = utils.Class2.Class2()

You could do a number of things here. For example, you could have a module called "resources" like this:

base ->
    utils ->
        resources.py

which contains both Class1 and Class2. Then you could do something like:

import utils.resources


c1 = utils.resources.Class1()

etc. But the key is that classes != files in python

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That hit the nail on the head :) I was incorrectly leveraging previous OO knowledge :)
0

did you import your classes into the main.py of the utils module? just add to utils/init.py:

from Class1 import Class1
from Class2 import Class2

then in your main.py, "import utils" will import those files as utils.Class1 etc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.