A Module is like a code library in python, module allows to logically organize code in any Python application.
For example, think of a situation when you want to create an application for school, there you may need to create a module for student and another module for teacher.
Actually module is a python file, where you want to write a group of functionalities, object definition etc. so that can easy to use and maintain the code base for future enhancement.
So, for school application we can create two modules student.py and teacher.py
Let’s look at the following picture to understand python packages and modules
As you can see we have created two modules in school package in above application, we have also used a base class (People) to explain how inheritance works in python, but before we explain more about how to write function in each module an create a new instance of any class to access the function, let’s understand the package in python.
To create a package in python, you need to create a folder, and then add all relevant files in that folder those need to be a part of that package, finally add a __init__.py file in that folder.
__init__.py file can be kept empty
class __init__(object): """description of class"""
So in above picture we have demonstrated a project structure with module and package concept in python.
Let's try to create same structure in your local environment!
Here are the steps
Here in Student class we have created some properties with and without default values and a method to print the person name.
class Student(object): def __init__(self, fname, lname): self.first_name = fname self.last_name = lname self.Mobile; self.Address; self.Email; def personName(self): print(self.first_name, self.last_name)
Now in Main class we create a new instance of Student class and access the "personName" method, but before that we need to import the Student class.
So the syntax is from PackageName.ModuleName Import ClassName
from School.Student import Student class Main(object): student = Student(); student.first_name="Michael"; student.last_name="Collins"; student.personName();
Here in above example, class name and module name are the same, but you can have different class name, also you can add multiple classes in the same module.