开发者

Tricky module import with late init

I have such a simple module's structure:

mod1/
    __init__.py
    clsOne.py
    clsN.py

Where code looks like this:

__init__.py:
     # module init
     from clsOne import MyFirstCLass
     from clsN import NThCLass

     clshnd = MyFirstClass()
     ...
     nhnd = NThClass()

clsOne.py:
     class MyFirstClass( object ):
         pass
clsN.py:
     classNThClass( object ):
         pass

Now I use them as follows:

Way #1) 
    from mod1.clsOne import MyFirstClass

or:

Way #2) 
    from mod1 import clshnd 

Is it possible to import name clshnd but in such a way that other handlers (i.e. nhnd) are initialized only on demand (when explicitelly imported)?

For now both: Way #1 and Way #2 cause module initialization call, means: also NThClass object is created. I would like to avoid it, because I have a lot of such classes and would like to avoid long init, however I would like to have simple access (Way #2) as well.

开发者_如何学Python Is it possible at all or I have to redesign modules and files (remove from init)?

Zbigniew


You just put the relevant code into a separate module.

mod1/
    __init__.py
    clsOne.py
    clsN.py
    foo.py

And then in foo.py:

from clsOne import MyFirstCLass
from clsN import NThCLass

clshnd = MyFirstClass()
...
nhnd = NThClass()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜