[Tutor] Default class in module
Kent Johnson
kent37 at tds.net
Thu Aug 11 14:27:18 CEST 2005
Jan Eden wrote:
> Hi,
>
> I'd like to pack some modules in a package. Each module contains a single class, which forces me to
>
> from Pythonsite.Show import Page
> page = Page()
> ...
>
> class Page(Site.DB): #class DB from module Site in package Pythonsite
> ...
>
> Is there a way to define a default class for a module which would me allow to
>
> from Pythonsite import Show
> page = Show() #page as an instance of default class in Show
>
> class Page(Site): #Page as a subclass of default class in Site
I don't know of any way to do exactly what you ask. However you can use the __init__.py module of the package to promote classes to package level visibility.
For example suppose you have
mypackage/
__init__.py - empty
myclass.py - defines MyClass
myotherclass.py - defines MyOtherClass
To use this you would for example
from mypackage.myclass import MyClass
mc = MyClass()
But if you put these lines in __init__.py:
from mypackage.myclass import MyClass
from mypackage.myotherclassimport MyOtherClass
this brings the class names into the module namespace. Now you can say
from mypackage import MyClass
mc = MyClass()
I suppose you could do your example by including this line in __init__.py:
from Pythonsite import Show
Show = Show.Page
Then clients that say
from Pythonsite import Show
will actually get Show.Page which is what Pythonsite.Show is now bound to, but that seems unneccesarily twisted and obscure to me.
HTH
Kent
More information about the Tutor
mailing list