Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

คำสั่ง from...import ใน Python (Import Specific)

from module import name นำเข้าชื่อเฉพาะตัว เข้า Namespace โดยตรง (ไม่ต้อง Prefix)

ตัวอย่าง

>>> from math import sin
>>> sin(0)
0.0
# ไม่ต้องเขียน math.sin()

Alias (เปลี่ยนชื่อ)

>>> from math import cos as cosine
>>> cosine(0)
1.0

Import หลายชื่อ

>>> from math import sin, cos, pi, sqrt
>>> from os.path import join, exists, basename

ข้อดี

  • Code สั้น กระชับ (ไม่ต้อง module. ซ้ำ)
  • ชัดเจนว่าใช้ชื่ออะไรจาก Module นั้น
  • Static Analysis Tools เข้าใจง่าย

ข้อควรระวัง

  • ชื่อชนกับ Local Variable → Bug แอบแฝง
  • Circular Import Risk เพิ่มขึ้น
  • ไม่ควร from module import *