This is a common task in Python programming, and it can be done in a few different ways.
Defining a module
A module is a Python file with a .py
extension. It can contain functions, classes, variables, and other Python objects. To define a module, simply create a new file with a .py
extension and add your code to it.
For example, the following code defines a module called arith.py
:
def add(a, b):
"""Adds two numbers together.
Args:
a: A number.
b: Another number.
Returns:
The sum of a and b.
"""
return a + b
def subtract(a, b):
"""Subtracts two numbers from each other.
Args:
a: A number.
b: Another number.
Returns:
The difference between a and b.
"""
return a - b
def multiply(a, b):
"""Multiplies two numbers together.
Args:
a: A number.
b: Another number.
Returns:
The product of a and b.
"""
return a * b
def divide(a, b):
"""Divides two numbers by each other.
Args:
a: A number.
b: Another number.
Returns:
The quotient of a and b.
"""
return a / b
This module defines four functions: add()
, subtract()
, multiply()
, and divide()
. These functions can be used to perform basic arithmetic operations on numbers.
Importing a module
To import a module into another Python program, you use the import
statement. For example, the following code imports the arith.py
module:
import arith
Once the module has been imported, you can access its functions and other objects using the module name. For example, the following code calls the add()
function from the arith
module:
result = arith.add(1, 2)
The variable result
will now contain the value 3.
Importing a specific function from a module
You can also import a specific function from a module using the from
statement. For example, the following code imports the add()
function from the arith
module:
from arith import add
Once you have imported a specific function from a module, you can call it directly without having to prefix it with the module name. For example, the following code calls the add()
function without having to prefix it with the arith
module name:
result = add(1, 2)
Example
The following example shows how to define a module and import a specific function from that module to another program:
# arith.py
def add(a, b):
"""Adds two numbers together.
Args:
a: A number.
b: Another number.
Returns:
The sum of a and b.
"""
return a + b
# main.py
from arith import add
result = add(1, 2)
print(result)
Output:
3
Conclusion
Defining and importing modules is a common task in Python programming. It allows you to organize your code into reusable blocks and to share your code with other Python programmers.
0 Comments