Multiple instances of modules
Peter Otten
__peter__ at web.de
Mon Sep 15 12:10:00 EDT 2003
Daniel Pryde wrote:
> Hi there.
>
> I'm currently trying to learn Python, my aim being to create my final
> year project at university using only Python instead of Java. I've run
> into a problem though while trying to make multiple instances of
> modules.
>
> For example, say I made a CD.py module which held details of an audio
> compact dic (album name, track names, etc..), and wanted my Python
> script to make a record collection using multiple CD's, I can't make
> them seperately. I tried using the 'import module as name' format, but
> any changes made to one instance affects the other. I assume this is
> because Python is simply referencing the one instance of CD.py rather
> than seperate ones. Is there a solution to this that doesn't involve
> using cPython or Jython? Any help would be greatly appreciated.
There is no connection between a class name and a module name enforced by
the language. If you already know a programming language, I strongly
recommend the tutorial that comes with the python distribution.
Below is a minimalist CD class with an example usage to get you started.
(In Python you say CD() instead of Java's new CD())
#module cd.py
class CD:
def __init__(self, composer, title):
self.composer = composer
self.title = title
def __str__(self):
return "%s: %s" % (self.composer, self.title)
#end module cd.py
#module main.py
from cd import CD
cdcoll = []
cdcoll.append(CD("Orff", "Carmina Burana"))
cdcoll.append(CD("Bach", "Goldberg-Variationen"))
for disk in cdcoll:
print disk
#end module main.py
Peter
More information about the Python-list
mailing list