Notes & software courses · Free to learn
Aph's Blog
On this page

วันที่ 12 — โมดูล (Modules)

👋 อ่านฟรีทั้งหมดบน Aph's Blog — เนื้อหาภาษาไทย ทำตามทีละหน้าใน sidebar ได้เลย หากมีข้อเสนอแนะหรืออยากให้เพิ่มหัวข้อไหน บอกได้เสมอ

เรียนรู้การสร้างและนำเข้า Module ใน Python ทั้ง custom modules และ built-in modules เช่น os, sys, math, statistics, string และ random

โมดูล (Modules)

Module คืออะไร

Module คือไฟล์ที่มีชุดของโค้ดหรือ functions ที่นำมาใช้งานใน application ได้ Module อาจเป็นไฟล์ที่มีแค่ตัวแปรเดียว, function เดียว หรือโค้ดขนาดใหญ่ก็ได้

การสร้าง Module

ในการสร้าง module เราเขียนโค้ดใน Python script แล้วบันทึกเป็นไฟล์ .py สร้างไฟล์ชื่อ mymodule.py ในโฟลเดอร์ project:

python
# mymodule.py file
def generate_full_name(firstname, lastname):
    return firstname + ' ' + lastname

สร้างไฟล์ main.py ในโฟลเดอร์ project แล้ว import ไฟล์ mymodule.py

การนำเข้า Module

ในการนำเข้าไฟล์เราใช้ keyword import และชื่อของไฟล์เท่านั้น:

python
# main.py file
import mymodule
print(mymodule.generate_full_name('Asabeneh', 'Yetayeh')) # Asabeneh Yetayeh

การนำเข้า Functions จาก Module

เราสามารถมี functions หลายตัวในไฟล์และนำเข้าได้หลายแบบ:

python
# main.py file
from mymodule import generate_full_name, sum_two_nums, person, gravity
print(generate_full_name('Asabneh','Yetayeh'))
print(sum_two_nums(1,9))
mass = 100
weight = mass * gravity
print(weight)
print(person['firstname'])

การนำเข้า Functions และเปลี่ยนชื่อ

ตอนนำเข้าเราสามารถเปลี่ยนชื่อของ module ได้:

python
# main.py file
from mymodule import generate_full_name as fullname, sum_two_nums as total, person as p, gravity as g
print(fullname('Asabneh','Yetayeh'))
print(total(1, 9))
mass = 100
weight = mass * g
print(weight)
print(p)
print(p['firstname'])

การนำเข้า Built-in Modules

เช่นเดียวกับภาษาโปรแกรมอื่น เราสามารถนำเข้า modules โดยใช้ keyword import built-in modules ที่ใช้บ่อย: math, datetime, os, sys, random, statistics, collections, json, re

OS Module

Python os module ช่วยให้ทำงาน operating system ต่าง ๆ โดยอัตโนมัติ มี functions สำหรับสร้าง, เปลี่ยน working directory, ลบ directory และดึงเนื้อหา:

python
# import the module
import os
# Creating a directory
os.mkdir('directory_name')
# Changing the current directory
os.chdir('path')
# Getting current working directory
os.getcwd()
# Removing directory
os.rmdir()

Sys Module

sys module มี functions และตัวแปรสำหรับจัดการ Python runtime environment sys.argv return list ของ command line arguments ที่ส่งให้ Python script โดย index 0 คือชื่อ script และ index 1 คือ argument แรก:

python
import sys
#print(sys.argv[0], argv[1],sys.argv[2])  # this line would print out: filename argument1 argument2
print('Welcome {}. Enjoy  {} challenge!'.format(sys.argv[1], sys.argv[2]))

รันด้วย command line:

sh
python script.py Asabeneh 30DaysOfPython

ผลลัพธ์:

sh
Welcome Asabeneh. Enjoy  30DayOfPython challenge!

คำสั่ง sys ที่มีประโยชน์:

python
# to exit sys
sys.exit()
# To know the largest integer variable it takes
sys.maxsize
# To know environment path
sys.path
# To know the version of python you are using
sys.version

Statistics Module

statistics module มี functions สำหรับสถิติทางคณิตศาสตร์ของข้อมูลตัวเลข functions ที่นิยมคือ mean, median, mode, stdev:

python
from statistics import * # importing all the statistics modules
ages = [20, 20, 4, 24, 25, 22, 26, 20, 23, 22, 26]
print(mean(ages))       # ~22.9
print(median(ages))     # 23
print(mode(ages))       # 20
print(stdev(ages))      # ~2.3

Math Module

module ที่มีการดำเนินการทางคณิตศาสตร์และค่าคงที่ต่าง ๆ:

python
import math
print(math.pi)           # 3.141592653589793, pi constant
print(math.sqrt(2))      # 1.4142135623730951, square root
print(math.pow(2, 3))    # 8.0, exponential function
print(math.floor(9.81))  # 9, rounding to the lowest
print(math.ceil(9.81))   # 10, rounding to the highest
print(math.log10(100))   # 2, logarithm with 10 as base

ใช้ help(math) หรือ dir(math) เพื่อดู functions ทั้งหมดใน module นำเข้า function เฉพาะ:

python
from math import pi
print(pi)

นำเข้าหลาย functions พร้อมกัน:

python
from math import pi, sqrt, pow, floor, ceil, log10
print(pi)                 # 3.141592653589793
print(sqrt(2))            # 1.4142135623730951
print(pow(2, 3))          # 8.0
print(floor(9.81))        # 9
print(ceil(9.81))         # 10
print(log10(100))         # 2

นำเข้าทุก function ด้วย *:

python
from math import *
print(pi)            # 3.141592653589793, pi constant
print(sqrt(2))       # 1.4142135623730951, square root
print(pow(2, 3))     # 8.0, exponential function
print(floor(9.81))   # 9, rounding to the lowest
print(ceil(9.81))    # 10, rounding to the highest
print(log10(100))    # 2, logarithm with 10 as base

หรือเปลี่ยนชื่อเมื่อ import:

python
from math import pi as PI
print(PI) # 3.141592653589793

String Module

string module มีประโยชน์หลายอย่าง:

python
import string
print(string.ascii_letters) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits)        # 0123456789
print(string.punctuation)   # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Random Module

random module ใช้สร้างตัวเลขสุ่ม ฟังก์ชัน random() return ค่าระหว่าง 0 ถึง 0.9999 ส่วน randint() return เลขจำนวนเต็มสุ่มใน range ที่กำหนด:

python
from random import random, randint
print(random())   # it doesn't take any arguments; it returns a value between 0 and 0.9999
print(randint(5, 20)) # it returns a random integer number between [5, 20] inclusive

💻 แบบฝึกหัด — วันที่ 12

ระดับ 1

  1. เขียน function ที่สร้าง random_user_id ความยาว 6 ตัวอักษร/ตัวเลข:
python
print(random_user_id())
'1ee33d'
  1. แก้ไข task ก่อนหน้า ประกาศ function ชื่อ user_id_gen_by_user ไม่รับ parameters แต่รับ 2 inputs จาก input() โดย input แรกคือจำนวนตัวอักษรและ input ที่สองคือจำนวน IDs ที่ต้องการสร้าง:
python
print(user_id_gen_by_user()) # user input: 5 5
#output:
#kcsy2
#SMFYb
#bWmeq
#ZXOYh
#2Rgxf

print(user_id_gen_by_user()) # 16 5
#1GCSgPLMaBAVQZ26
#YD7eFwNQKNs7qXaT
#ycArC5yrRupyG00S
#UbGxOFI7UXSWAyKN
#dIV0SSUTgAdKwStr
  1. เขียน function ชื่อ rgb_color_gen ที่สร้างสี RGB (ค่า 3 ตัวในช่วง 0-255 แต่ละตัว):
python
print(rgb_color_gen())
# rgb(125,244,255) - the output should be in this form

ระดับ 2

  1. เขียน function list_of_hexa_colors ที่ return จำนวนสีแบบ hexadecimal ที่ต้องการในรูปแบบ array (6 ตัวอักษรหลังจาก # โดยใช้เลข 0-9 และตัวอักษร a-f)
  2. เขียน function list_of_rgb_colors ที่ return จำนวนสี RGB ที่ต้องการในรูปแบบ array
  3. เขียน function generate_colors ที่สร้างสีแบบ hexa หรือ rgb ตามจำนวนที่ต้องการ:
python
generate_colors('hexa', 3) # ['#a3e12f','#03ed55','#eb3d2b']
generate_colors('hexa', 1) # ['#b334ef']
generate_colors('rgb', 3)  # ['rgb(5, 55, 175','rgb(50, 105, 100','rgb(15, 26, 80']
generate_colors('rgb', 1)  # ['rgb(33,79, 176)']

ระดับ 3

  1. เรียก function ของคุณว่า shuffle_list รับ list เป็น parameter แล้ว return list ที่สับเปลี่ยนลำดับแล้ว
  2. เขียน function ที่ return array ของตัวเลขสุ่ม 7 ตัวในช่วง 0-9 โดยทุกตัวต้อง unique