2

I am new to python and found that I can import a module without importing any of the classes inside it. I have the following structure --

myLib/
    __init__.py
    A.py
    B.py

driver.py

Inside driver.py I do the following --

import myLib
tmp = myLib.A()

I get the following error trying to run it. AttributeError: 'module' object has no attribute A

Eclipse does not complain when I do this, in fact the autocomplete shows A when I type myLib.A.

What does not it mean when I import a module and not any of the classes inside it?

Thanks

P

R11
  • 405
  • 2
  • 6
  • 15

2 Answers2

4

Python is not Java. A and B are not classes. They are modules. You need to import them separately. (And myLib is not a module but a package.)

The modules A and B might themselves contain classes, which might or might not be called A and B. You can have as many classes in a module as you like - or even none at all, as it is quite possible to write a large Python program with no classes.

To answer your question though, importing myLib simply places the name myLib inside your current namespace. Anything in __init__.py will be executed: if that file itself defines or imports any names, they will be available as attributes of myLib.

If you do from myLib import A, you have now imported the module A into the current namespace. But again, any of its classes still have to be referenced via the A name: so if you do have a class A there, you would instantiate it via A.A().

A third option is to do from myLib.A import A, which does import the class A into your current namespace. In this case, you can just call A() to instantiate the class.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

You need to do

from mylib import A

Because A is not an attribute of __init__.py inside mylib

When you do import mylib it imports __init__.py

See my answer. About packages

Community
  • 1
  • 1
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91