Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

Multiple classes in a Python module

I'm very new to Python (I'm coming from a JAVA background) and I'm wondering if anyone could help me with some of the Python standards. Is it a normal or "proper" practice to put multiple class in a module? I have been working with Django and started with the tutorials and they place their database model classes in the same module. Is this something that is normally done or should I stick with 1 class per module? Is there a reason I would do one over the other?

Hope I'm being clear and not to generic. Thanks to everyone in advance!

question from:https://stackoverflow.com/questions/2634394/multiple-classes-in-a-python-module

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a useful rule of thumb from what I have seen of typical Java projects:

The bottom-most package in Java should be a file in Python

What does that mean? If your Java project was organized:

toplevel/
   subproject/
        Foo.java
        Bar.java
   subproject2/
        Baz.java
        Qux.java

Then your Python project should look like:

toplevel/
    subproject.py <-- put class Foo, Bar here
    subproject2.py <-- put class Baz, Qux here

Things to notice re: organization:

  • Do not use inner classes. Just put classes in the same module
  • By convention, things that start with _ are "private"
  • It's OK to have "public variables"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...