How to organise classes and modules

Diez B. Roggisch deets at nospam.web.de
Mon May 15 08:07:14 EDT 2006


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

You misunderstood that you'd have to create an instance first before
invoking a method on that very instance. That is the same in C++, btw.

> 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?

I'm not sure what you mean by ugly. If you mean by ugly that you have to
instantiate an object before using it - that is the way it works in _all_
OO languages. 

If you mean that you find it ugly to have long modulenames that are the same
as the class-name - yes it is ugly - but that is utterly your personal
decision to do so. In python, modules usually contain several classes, and
the module name groups them by function and has a name related to that
function. So most of the times one writes

import module

o = module.Class()

Which is not ugly - IMHO at least :) Especially not more ugly than using C++
namespaces, isn't it? And that is what a module essentially is: a
namespace. 


> 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.

You seem to have some troubles with OO in general and with the way python
does it. So I think it is kind of funny if you claim it is something to
strive for. OO is no silver bullet - if you have something that can be
dealt with using a function, it's perfectly good design to use one. Having
objects just for the sake of it introduces all sorts of problems, related
to unnecessary state, unclear implementation smeared over  several methods
an the like.

> 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?

Group classes that belong to the same domain in one module. Import that,
possibly using an alias like

import MyLongDescriptiveModuleName as mn

don't fall for the temptation to use

from MyLongDescriptiveModuleName import *

as it will cause only more headache!

Diez



More information about the Python-list mailing list