Python: Custom package delivered with script and ways of importing it -


i trying grok way packages work in python. goal require python installed, users should able check out script repository , 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 testpackage.py"  the_instance = someclass()  the_instance.hi() 

contents of mypackage/_init_.py:

class insideinitpy():     def hi(self):         print "hi insideinitpy! (when importing package)"  insideinitpy().hi() 

contents of mypackage/someclass.py:

class someclass():     def hi(self):         print "hi someclass in package! (using explicit call)" 

when running test script python testpackage.py:

hi insideinitpy! (when importing package) hello testpackage.py traceback (most recent call last):   file "testpackage.py", line 5, in <module>     the_instance = someclass() typeerror: 'module' object not callable 

the line producing error the_instance = someclass(). hi insideinitpy! (when importing package) written console when importing seems package can found.

how example working (as pros , cons to) using these variants of first line in testpackage.py with:

  1. from mypackage import someclass
  2. from mypackage import *
  3. import mypackage

does affect import if user standing in same directory testpackage.py or not?

don't confuse classes modules.

you have file someclass.py. files correspond modules. import someclass gives module.

inside someclass.py have class definition. class someclass.someclass. need write

the_instance = someclass.someclass() 

alternatively, import class someclass module mypackage.someclass:

from mypackage.someclass import someclass 

Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -