views:

93

answers:

2

Much like Java (or php), I'm use to seperating the classes to files.
Is it the same deal in Python? plus, how should I name the file?
Lowercase like classname.py or the same like ClassName.py?
Do I need to do something special if I want to create an object from this class or does the fact that it's in the same "project" (netbeans) makes it ok to create an object from it?

+4  A: 

In Python, one file is called a module. A module can consist of multiple classes or functions.

As Python is not an OO language only, it does not make sense do have a rule that says, one file should only contain one class.

One file (module) should contain classes / functions that belong together, i.e. provide similar functionality or depend on each other.
Of course you should not exaggerate this. Readability really suffers if your module consist of too much classes or functions. Then it is probably time to regroup the functionality into different modules and create packages.


For naming conventions, you might want to read PEP 8 but in short:

Class Names

Almost without exception, class names use the CapWords convention. Classes for internal use have a leading underscore in addition.

and

Package and Module Names

Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short -- this won't be a problem on Unix, but it may be a problem when the code is transported to older Mac or Windows versions, or DOS.


To instantiate an object, you have to import the class in your file. E.g

>>> from mymodule import MyClass
>>> obj = MyClass()

or

>>> import mymodule
>>> obj = mymodule.MyClass()

or

>>> from mypackage.mymodule import MyClass
>>> obj = MyClass()

You are asking essential basic stuff, so I recommend to read the tutorial.

Felix Kling
Also for naming see PEP8 http://www.python.org/dev/peps/pep-0008/
Mark
Ok, since it's called a module, do I need to import it ? and if so, let's say my file name is site.py and I want to use the classes from it in my other file blabla.py, do I write something likeimport site.py ?
Asaf
@Asaf: See my updated answer. How you have to import depends on different things. If the modules are in the same package you can just import the module. If not, you have to import the package too. **Never** include the file suffix (i.e. `.py`). Read the tutorial and search here on SO about how to import correctly. This question was already asked.
Felix Kling
A: 

No, you can define multiple classes (and functions, etc.) in a single file. A file is also called a module.

To use the classes/functions defined in the module/file, you will need to import the module/file.

Chris Henry