Reputation: 4217
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 TestPackage.py Mypackage/
):
TestPackage.py
Mypackage/:
__init__.py
SomeClass.py
Contents of TestPackage.py:
from Mypackage import SomeClass
print "Hello from TestPackage.py"
the_instance = SomeClass()
the_instance.hi()
Contents of Mypackage/_init_.py:
class InsideInitPy():
def hi(self):
print "Hi from InsideInitPy! (when importing package)"
InsideInitPy().hi()
Contents of Mypackage/SomeClass.py:
class SomeClass():
def hi(self):
print "Hi from SomeClass in the package! (using explicit call)"
When running the test script python TestPackage.py
:
Hi from InsideInitPy! (when importing package)
Hello from TestPackage.py
Traceback (most recent call last):
File "TestPackage.py", line 5, in <module>
the_instance = SomeClass()
TypeError: 'module' object is not callable
The line producing an error is the_instance = SomeClass()
. As 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 TestPackage.py
with:
from Mypackage import SomeClass
from Mypackage import *
import Mypackage
Does it affect the import if the user is standing in the same directory as TestPackage.py or not?
Upvotes: 1
Views: 128
Reputation: 123632
Don't confuse classes with modules.
You have a file SomeClass.py
. Files correspond to modules. So import SomeClass
gives you a module.
Inside SomeClass.py
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
from the module MyPackage.SomeClass
:
from MyPackage.Someclass import SomeClass
Upvotes: 3
Reputation: 798566
Python is not Java.
from Mypackage.SomeClass import SomeClass
Upvotes: 3