Module shine fili .py guda daya; kuɗi shine jerin directoris na moduli. Shigo yana ba ka damar yin amfani da code daga sauran moduli, dandana-dandana bangare na aiki na sake amfani da su.
Moduli da shigo
(): a + b
PI =
# main.py — different ways to import
import math_utils # import the whole module
math_utils.add(2, 3) # access via the module name
from math_utils import add, PI # import specific names
add(2, 3) # use directly
from math_utils import add as plus # import with an alias
import numpy as np # common aliasing convention
mypackage/
__init__.py ← marks it as a package (can be empty)
module_a.py
subpackage/
__init__.py
module_b.py
from mypackage.module_a import something
from mypackage.subpackage.module_b import other
Filin __init__.py yana nuna directory a matsayin kuɗi (kuma zai iya gudna kuɗi-init code ko bayyana abin da from package import * yana bayyana).
if __name__ == "__main__"def main():
print("running as a script")
if __name__ == "__main__": # True only when run directly, not when imported
main()
Wancan ya bar fili yafiya azaman module na shigo da script mai aiki — code a karkashinsa yana aiki ne idan fili ya kasance a aiki kai tsaye (python file.py), ba lokacin da aka shigo ba. Hadirin Python kusan kowa.
import sys
sys.path # the list of directories Python searches for imports
# includes: the current directory, installed packages (site-packages), stdlib
import os, json, datetime # standard library — "batteries included"
import requests # third-party — installed via pip from PyPI
Moduli da kuɗi su ne yadda ka hada ma Python code cikin abubuwan da ake iya sake amfani, kyautattun gida maimakon fili guda mai girma — ainihi ne ga wani aiki da ba mai littafi ba.
Tunatarwa hadirin shigo, tsarin kuɗi (__init__.py), hadirin if __name__ == "__main__" (aiki biyu script/module), da yadda Python ke neman moduli (sys.path) yana da mahimmanci don yin tsarin aike, sake amfani code, da yin amfani da gida-standard library da kuma PyPI ekosistem.
Kuskure na shigo da rikicewa hadirin-hadirin abubuwan nishi ne na farko waɗanda ilimin nan ya warware.