[Tutor] creation of a module
Cedric BRINER
work at infomaniak.ch
Fri May 13 21:27:16 CEST 2005
> > hi,
> >
> > 1)
> > I'm trying to create my _first_ own module. I've decided to write each class into a separate file.
OB> >
> > /MyModule|-bunch.py
> > |-a.py
> > |-b.py
> > `-c.py
>
> You also need MyModule/__init__.py to signal to Python that MymModule is a package. (Actually you
> are creating a package containing several modules.)
thank you to enlight me.. :).. that I was creating a package containing many modules. Maybe I'm smarter than I thought.
> > {a,b,c}.py contains respecetively classA,classB,classC more some unittest
> > and bunch.py will contains some usefull function using the class{A,B,C}
> >
> > I'd like that when I import MyModule (`import MyModule')OB
> > I'll see from it:
> > MyModule.classA
> > .classB
> > .classC
> > .<function1 in numch.py>
> > .<function2 in numch.py>
> > ...
> > without seeing MyModule.{a,b,c}
>
> In MyModule/__init__.py put
> from MyModule.a import classA
> from MyModule.b import classB
> from MyModule.c import classC
I've done it. But is it normal that I'see also the filename
MyModule.classA
.classB
.classC
.a <---- not expected
.b <--'
.c <-'
.<function1 in numch.py>
.<function2 in numch.py>
can I not import them ?
> This creates package-level attributes for the classes.
>
> > 2) does someone now how to do this:
> > x=3
> > with a function like:
> > assign('x',3)
>
> Can you say why you want to do this? It is possible but generally it is better to use a dict:
> values = {}
> values['x'] = 3
>
the idea was to automate the :
from MyModule.a import classA
from MyModule.b import classB
from MyModule.c import classC
with a loop
<snip>
lclassname=['classA', 'classB', 'classC']
#in the future I can even automate the creation of classname list
for classname in lclassname:
#filename='a', classname='classA'
filename=classname.replace('class','').lower()
#from filename import classname
#can't do this
module=__import__(filename, gloabls(), locals(), [classname])
classDefinition=getattr(module,classname)
assign(classname,classDefinition)
<snip>
In this way, when I'll do an
import FWobs
I'll get:
MyModule.classA
.classB
.classC
.<function1 in numch.py>
.<function2 in numch.py>
thanks for your help !
--
Cedric BRINER
More information about the Tutor
mailing list