how to arrange classes in .py files?

Kent kent.yuan at gmail.com
Fri Mar 27 21:43:58 CET 2009


On Mar 27, 3:01 pm, "David L. Jones" <david.l.jo... at gmail.com> wrote:
> On Mar 26, 8:51 pm, Kent <kent.y... at gmail.com> wrote:
>
> > ... Is
> > there any convention how to manage python classes into .py files?
>
> > ...
> > In above packages, each .py file contains one python class. And
> > ClassName = Filename
>
> > ...
> > Can anyone give some hint on it? would be great with reason.
>
> Overall, I don't think there is a single convention that anyone can
> point to and everyone will at least acknowledge as convention.
>
> If you have multiple single-class files, then you will have
> unnecessary redundancy referencing the classes from outside:
>
>   # Module structure:  mymodule/
>   #                      __init.py__
>   #                      someclass.py
>   import mymodule
>   c = mymodule.someclass.someclass()
>
> You can get around this with a Java-like statement:
>
>   # Same module structure
>   from mymodule.someclass import someclass  # or from ... import *
>   c = someclass()
>
> but you lose namespacing which can make code more difficult to read. I
> think that this Java-style approach of pulling everything into the
> current namespace is quite silly, since Python's module structure was
> specifically designed in large part not to work like this. (Commence
> flaming.)
>
> I tend to think in terms of coupling and cohesion. Within an
> application, any classes, functions, data, etc. that are tightly
> coupled are candidates to live in the same file. If you have a set of
> classes that all inherit from a common set of base classes, then you
> should probably consider putting the base and inherited classes
> together in a file. That puts them in the same namespace, which makes
> sense.
>
> Cohesion is the flip side: if a class is large, even if it is somewhat
> coupled to other classes, it should probably go in its own file. In
> general, use coupling as a guide to put more things into a single
> file, and cohesion as a guide to break out parts into multiple files.
>
> D

thanks you guys' explaination. I did some refactory on my codes. Now
it look's like:

myapp/ # this is a package, it is the root package
   - gui/ # this is package, contains all gui related modules
        - mainFrame.py


   - dao.py # all daos are in this module
   - service.py # all service classes, responsible for handling DB
connections, Txn mgmt, and Business logic Task (calling daos)
   - entity.py  # like 'pojo's, in java,
   - util.py # utils
   - myapp.py # start main script


with this structure, import statements were *significantly*
reduced. :)






More information about the Python-list mailing list