Module kuma mahimman ra'ayoyi guda biyu ne don tsarawa da sarrafa lambar tushe. Ga bayanin da kuma yadda ake amfani da su: package Python module package
Module
- A cikin Python, a module tarin ma'anoni ne, ayyuka, masu canji, da maganganun da aka rubuta don amfani.
- Python Ana iya ɗaukar kowane fayil a matsayin module kuma ya ƙunshi lamba mai alaƙa da takamaiman aiki.
- Kuna iya amfani da ginannen ciki ko ƙirƙirar naku don amfani da lambar ku. Python module module
Misali: Ƙirƙiri fayil mai suna math_operations.py
mai ɗauke da wasu ayyukan lissafi:
# math_operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a- b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
Bayan haka, zaku iya amfani da waɗannan ayyuka a cikin wani shirin ta shigo da math_operations
module:
# main.py
import math_operations
result = math_operations.add(10, 5)
print(result) # Output: 15
Package
- A package hanya ce ta tsarawa da haɗin gwiwa tare. module
- Littafin shugabanci ne wanda ya ƙunshi Python fayiloli( ) da fayil mara komai don nuna cewa kundin adireshi. module
__init__.py
package - Package Taimaka tsara lambar ku cikin ma'auni na ma'ana da kundayen adireshi da aka tsara.
Misali: Ƙirƙiri mai packageuna, mai ɗauke da biyu da: my_package
module module1.py
module2.py
my_package/
__init__.py
module1.py
module2.py
A cikin module1.py
, muna da lamba mai zuwa:
# module1.py
def greet(name):
return f"Hello, {name}!"
A cikin module2.py
, muna da lamba mai zuwa:
# module2.py
def calculate_square(num):
return num ** 2
Bayan haka, zaku iya amfani da ayyuka daga cikin kamar haka: module my_package
package
# main.py
from my_package import module1, module2
message = module1.greet("Alice")
print(message) # Output: Hello, Alice!
result = module2.calculate_square(5)
print(result) # Output: 25
Amfani da taimaka muku tsarawa da sarrafa lambar ku yadda ya kamata, yana sa ta zama abin karantawa da kiyayewa. module package