How to create a user defined package in python???

Package is a collection of files which contains various member functions and its definitions. When a user creates a package with their own definition, it can be considered as a module. It can be reused anywhere.

Let us create a package in your system by creating a folder “greetings” by right click in the folder. Choose “new” option and select new folder. Name it as “greetings”.

Next, create three files. One is “__init__.py”,other two’s are “greet1.py” and “greet2.py”.

It look like below.

greetings

     |-------   __init__.py  

     |-------   greet1.py

     |-------   greet2.py

 __init__.py is a file which represents a initialization file. it denotes the it belongs to a package.

greet1.py and greet2.py defines the member functions.

Here ,it contains the below code.

“greet1.py”

#This file has a definition of function “message1” as a print statement.

def message1():

              print("Welcome to the world of python")

 

“greet2.py”

#It defines a function “message2’” with displaying greetings message.

def message2():

              print("Enjoy coding")

Now ,its time to use this package “greetings” to an external file “Test.py”

Steps:

  • Open a text editor like notepad, save it as a python file “Test.py”
  • Add the code to the file.

#import the package “greetings” and its sub modules “greet1,greet2”

from greetings import greet1,greet2

#call the functions by mentioning the filename followed by. with function.

greet1.message1()

greet2.message2()

Next, execute the file in command prompt. Set the path for folder. Execute the file “Test.py”. you will get the below output.

 

This is the simple way to create a package in python is explained.

No comments:

Post a Comment