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

วิธี Import ไฟล์ Python อื่นๆ

ต้อง import ก่อนจึงจะใช้แพ็กเกจ/โมดูลได้ ใน Python บางอย่างเป็น built-in (เช่น int, float) ใช้ได้ทันที แต่อื่นๆ ต้อง import ก่อน

ตัวอย่าง

>>> math.cos(0)
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'math' is not defined
>>> import math
>>> math.cos(0)
1.0

สำหรับไฟล์ Python ของตัวเอง ใช้ import statement:

>>> import my_file  # สมมติมี my_file.py ใน current directory
# สำหรับไฟล์ในโฟลเดอร์อื่น ให้ระบุ path absolute หรือ relative