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?
No. Typical Python style is to put related classes in the same module. It may be that a class ends up in a module of its own (especially if it's a large class), but it should not be a goal in its own right.
In Python there is rule of one module=one file. In Python if you restrict yourself to one class per file (which in Python is not prohibited) you may end up with large number of small files – not easy to keep track. So depending on the scenario and convenience one can have one or more classes per file in Python.
There is no limit on how many classes one can put in a file or a module.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With