Using Class/function In Another Module
Solution 1:
In Python, every file you create is a module and a collection of modules can be logically grouped as a package. Python is little different than Java, which allows files in the same package to be used without importing explicitly.
Since a module is a namespace, whenever you use an identifier in a module, it must be defined in it, otherwise you will get a NameError
.
When you import a module,
import Mesh
Python understands that you have imported a module and all the items in it can be referenced with the module's name. If you do
Mesh('name')
you will get an error, because only the Mesh
module is imported in the current module, not the Mesh
class. That is why you have to explicitly specify
Mesh.Mesh('name')
It means that, you are telling Python that, I am referring to the Mesh
class in the Mesh
module, which I imported.
But in your case, you can import only the particular class from the Mesh
module into the current module's namespace, like this
fromMeshimportMesh
And then create an object of it, like this
Mesh('name')
Solution 2:
Well you can name your Mesh.py
something else more englobing, unlike Java you don't need class names in your .py module, and doesn't have to contain only one "top level class"
Otherwise you can also do
from Mesh import Mesh
Mesh('name')
Solution 3:
I have one class, Mesh.py
Right there is the problem. Mesh.py
is not a class, it's a file, which means it's a module.
In Python, you shouldn't automatically follow the Java pattern of putting each class in its own file. Break things up between multiple files if and when they become too large and unwieldy to fit in one file. If you have many small classes (and/or functions and other things), just put them in one file. Then you won't have to import anything. If you get to the point where you need to split things up among multiple files, you won't see imports as a problem, because at that point your codebase will be complex enough that the separation into multiple modules will increase code clarity.
Solution 4:
You don't have to import at all if you are referencing the class inside the module (i.e. Mesh.py) that has the definition. In that case, Mesh (the class) is in the module level namespace. That's worth noting because you can have as many classes a you want in a module.
The other way to get Mesh (the class) into the module level namespace is to import it from the module in which it is defined (or any other module that has imported it). Like:
from Mesh importMeshmesh= Mesh('name')
Post a Comment for "Using Class/function In Another Module"