On this page
วันที่ 12 — โมดูล (Modules)
เรียนรู้การสร้างและนำเข้า 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:
# mymodule.py file
def generate_full_name(firstname, lastname):
return firstname + ' ' + lastnameสร้างไฟล์ main.py ในโฟลเดอร์ project แล้ว import ไฟล์ mymodule.py
การนำเข้า Module
ในการนำเข้าไฟล์เราใช้ keyword import และชื่อของไฟล์เท่านั้น:
# main.py file
import mymodule
print(mymodule.generate_full_name('Asabeneh', 'Yetayeh')) # Asabeneh Yetayehการนำเข้า Functions จาก Module
เราสามารถมี functions หลายตัวในไฟล์และนำเข้าได้หลายแบบ:
# 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 ได้:
# 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 และดึงเนื้อหา:
# 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 แรก:
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:
python script.py Asabeneh 30DaysOfPythonผลลัพธ์:
Welcome Asabeneh. Enjoy 30DayOfPython challenge!คำสั่ง sys ที่มีประโยชน์:
# 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.versionStatistics Module
statistics module มี functions สำหรับสถิติทางคณิตศาสตร์ของข้อมูลตัวเลข functions ที่นิยมคือ mean, median, mode, stdev:
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.3Math Module
module ที่มีการดำเนินการทางคณิตศาสตร์และค่าคงที่ต่าง ๆ:
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 เฉพาะ:
from math import pi
print(pi)นำเข้าหลาย functions พร้อมกัน:
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 ด้วย *:
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:
from math import pi as PI
print(PI) # 3.141592653589793String Module
string module มีประโยชน์หลายอย่าง:
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 ที่กำหนด:
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
- เขียน function ที่สร้าง random_user_id ความยาว 6 ตัวอักษร/ตัวเลข:
print(random_user_id())
'1ee33d'- แก้ไข task ก่อนหน้า ประกาศ function ชื่อ user_id_gen_by_user ไม่รับ parameters แต่รับ 2 inputs จาก input() โดย input แรกคือจำนวนตัวอักษรและ input ที่สองคือจำนวน IDs ที่ต้องการสร้าง:
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- เขียน function ชื่อ rgb_color_gen ที่สร้างสี RGB (ค่า 3 ตัวในช่วง 0-255 แต่ละตัว):
print(rgb_color_gen())
# rgb(125,244,255) - the output should be in this formระดับ 2
- เขียน function list_of_hexa_colors ที่ return จำนวนสีแบบ hexadecimal ที่ต้องการในรูปแบบ array (6 ตัวอักษรหลังจาก # โดยใช้เลข 0-9 และตัวอักษร a-f)
- เขียน function list_of_rgb_colors ที่ return จำนวนสี RGB ที่ต้องการในรูปแบบ array
- เขียน function generate_colors ที่สร้างสีแบบ hexa หรือ rgb ตามจำนวนที่ต้องการ:
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
- เรียก function ของคุณว่า shuffle_list รับ list เป็น parameter แล้ว return list ที่สับเปลี่ยนลำดับแล้ว
- เขียน function ที่ return array ของตัวเลขสุ่ม 7 ตัวในช่วง 0-9 โดยทุกตัวต้อง unique