Modules

Python ระดับกลางสำหรับนักพัฒนา

Jasmin Ludolf

Senior Data Science Content Developer

Module คืออะไร?

  • Modules คือสคริปต์ Python
    • ไฟล์ที่มีนามสกุล .py
    • มีฟังก์ชันและแอตทริบิวต์
    • สามารถมี module อื่นอยู่ภายในได้

$$

$$

$$

  • ช่วยให้ไม่ต้องเขียนโค้ดที่มีอยู่แล้วซ้ำอีกครั้ง!

ชายมองภาพสะท้อนในกระจกซึ่งสะท้อนซ้ำต่อเนื่อง

Python ระดับกลางสำหรับนักพัฒนา

Python modules

  • os:
    • ใช้โต้ตอบกับระบบปฏิบัติการ
    • ตรวจสอบไดเรกทอรีปัจจุบัน
    • แสดงรายการไฟล์ที่มีอยู่
    • เข้าถึงตัวแปรสภาพแวดล้อม
  • string:
    • ช่วยลดความซับซ้อนในการประมวลผลข้อความ

Python modules

Python ระดับกลางสำหรับนักพัฒนา

การ import module

# General syntax
import <module_name>
# Import the os module
import os
# Check the type
print(type(os))
<class 'module'>
Python ระดับกลางสำหรับนักพัฒนา

ค้นหาฟังก์ชันของ module

# Call help()
# Warning - will return a very large output!
print(help(os))
Help on module os:

NAME
    os - OS routines for NT or Posix depending on what system we're on.

MODULE REFERENCE
    https://docs.python.org/3.12/library/os.html
    ...
Python ระดับกลางสำหรับนักพัฒนา

ดึงไดเรกทอรีทำงานปัจจุบัน

# Using an os function
print(os.getcwd())
/home/courses/intermediate_python_for_developers

$$

  • มีประโยชน์เมื่อต้องอ้างอิงไดเรกทอรีในภายหลัง
# Assign to a variable
work_dir = os.getcwd()
Python ระดับกลางสำหรับนักพัฒนา

การเปลี่ยนไดเรกทอรี

# Changing directory
os.chdir("/home/courses")
# Check the current directory
print(os.getcwd())
/home/courses
# Confirm work_dir has not changed
print(work_dir)
/home/courses/intermediate_python_for_developers
Python ระดับกลางสำหรับนักพัฒนา

แอตทริบิวต์ของ module

  • แอตทริบิวต์จะคืนค่า
  • ฟังก์ชันจะดำเนินการบางอย่าง
  • ไม่ใส่วงเล็บกับแอตทริบิวต์
# Get the local environment
print(os.environ)
environ{'PATH': '/usr/local/bin',
        'TERM': 'xterm',
        'HOSTNAME': '097a0fe4-d6ce-4325-a6e2-1d0ce2800c2b',
        'TZ': 'Europe/Brussels',
        'LANG': 'en_US.UTF-8',
         ...
Python ระดับกลางสำหรับนักพัฒนา

String module

import string


print(string.ascii_lowercase)
abcdefghijklmnopqrstuvwxyz

$$

  • ตรวจสอบว่าสตริงมีตัวอักษร ตัวเลข หรืออักขระเฉพาะหรือไม่

$$

  • เหมาะสำหรับตรวจสอบความถูกต้องของข้อมูลที่ผู้ใช้ป้อน 💡
print(string.digits)
0123456789

$$

print(string.punctuation)
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Python ระดับกลางสำหรับนักพัฒนา

มาฝึกกันเถอะ!

Python ระดับกลางสำหรับนักพัฒนา

Preparing Video For Download...