Are classes in Python in different files?

2019-03-12 00:39发布

问题:

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?

回答1:

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.



回答2:

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.