Python: paquete personalizado entregado con script y formas de importarlo

I am trying to grok the way packages work in Python. My goal is to only require that Python is installed, the users should simply be able to check out the script repository and run it.

The relevant files (output of ls Mypackage/):


Contenido de

from Mypackage import SomeClass

print "Hello from"

the_instance = SomeClass()


Contents of Mypackage/

class InsideInitPy():
    def hi(self):
        print "Hi from InsideInitPy! (when importing package)"


Contents of Mypackage/

class SomeClass():
    def hi(self):
        print "Hi from SomeClass in the package! (using explicit call)"

When running the test script python

Hi from InsideInitPy! (when importing package)
Hello from
Traceback (most recent call last):
  File "", line 5, in <module>
    the_instance = SomeClass()
TypeError: 'module' object is not callable

The line producing an error is the_instance = SomeClass(). La Hi from InsideInitPy! (when importing package) is written to the console when importing it seems the package can be found.

How do I get the example working (as well as pros and cons to) using these variants of first line in con:

  1. from Mypackage import SomeClass
  2. from Mypackage import *
  3. import Mypackage

Does it affect the import if the user is standing in the same directory as or not?

preguntado el 09 de marzo de 12 a las 16:03

Python's error messages are informative. If you get 'module' object is not callable then you are calling a module object. -

Well I still didn´t understand why I couldn´t call it. -

I´ll gain the knowledge to answer my three questions above and post an answer. Even though the provided answers helped me they didn´t answer the original question. I´ll take the time to write a longer answer myself later on, as it might help someone else when getting a hit on this question when searching. -

I don't understand what you mean "didn't answer the original question". Both answers certainly did! -

(which is not to discourage you from writing up your own answer -- that's a good idea =) -

2 Respuestas

Don't confuse classes with modules.

You have a file Files correspond to modules. So import SomeClass le da una módulo.

Inside you have a class definition. That class is SomeClass.SomeClass. So you would need to write

the_instance = SomeClass.SomeClass()

Alternatively, you could import the class SomeClass desde el modulo MyPackage.SomeClass:

from MyPackage.Someclass import SomeClass

respondido 09 mar '12, 16:03

Python no es Java.

from Mypackage.SomeClass import SomeClass

respondido 09 mar '12, 16:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.