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

Import ฟังก์ชันเดียวจากโมดูล Python (from ... import)

ใช้ from module import function นำเข้าฟังก์ชันเฉพาะตัว

ตัวอย่าง

>>> from math import sin
>>> sin(0)
0.0
# ใช้ sin() โดยตรง ไม่ต้อง math.sin()

Alias

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

เปรียบเทียบ

StyleCodeใช้งาน
Module Importimport math; math.sin(0)หลายฟังก์ชัน ชื่อชัดเจน
Specific Importfrom math import sin; sin(0)1-2 ฟังก์ชัน ใช้บ่อย
Aliasfrom math import cos as cosineชื่อชน หรือ อ่านง่ายขึ้น
PEP 8: ยอมรับได้ทั้งคู่ เลือกตาม Context ความสำคัญคือ Consistent ภายใน Project