How to organise classes and modules

Alex mizipzor at gmail.com
Mon May 15 13:18:46 CEST 2006


Hi, this is my first mail to the list so please correct me if Ive done
anything wrong.

What Im trying to figure out is a good way to organise my code. One
class per .py file is a system I like, keeps stuff apart. If I do
that, I usually name the .py file to the same as the class in it.

File: Foo.py
***********************
class Foo:
     def __init__(self):
          pass
     def bar(self):
          print 'hello world'

************************

Now, in my other module, I want to include this class. I tried these two ways:

>>> import Foo
>>> Foo.Foo.bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with Foo instance as
first argument (got nothing instead)

Some unbound method error. Have I missunderstood something or am I on
the right track here?

I did this to, almost the same thing:

>>> from Foo import Foo
>>> Foo.bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with Foo instance as
first argument (got nothing instead)

One thing that I tried that worked ok was this:

>>> import Foo
>>> instance=Foo.Foo()
>>> instance.bar()
hello world

But in my opinion, this is very ugly. Especially if the class names
are long, like my module/class TileDataBaseManager. But is this the
"right" way in python?

Another (ugly) way that Ive considered is the following. Break it out
of the class, save the functions in a file alone, import the file and
treat it like a class:

File: Foo2.py
***********************
def bar(self):
     print 'hello world'

************************

>>> import Foo2
>>> Foo2.bar()
hello world

Very clean from the outside. I would like something like this. But,
here, I loose the __init__ function. I have to call it manually that
is, which s not good. Also, maybe the biggest drawback, its no longer
in a class. Maybe its not that important in python but from what Ive
learned (in c++) object orientation is something to strive for.

So, to sum it up, I have one class in one file, both with the same
name. How do I store/import/handle it in a nice, clean and python-like
manner?

Thank you very much in advance.
/ Alex



More information about the Python-list mailing list