การใช้งาน Modularity ของ Python ในทางปฏิบัติ
ในสไลด์ เราได้พูดถึง 3 วิธีในการเขียนโค้ดแบบ Modular ด้วย Python ได้แก่ แพ็กเกจ (packages), คลาส (classes), และ เมธอด (methods) ดูโค้ดตัวอย่างที่เราทบทวนไปด้านล่างได้เลย
# Import the pandas PACKAGE
import pandas as pd
# Create some example data
data = {'x': [1, 2, 3, 4],
'y': [20.1, 62.5, 34.8, 42.7]}
# Create a dataframe CLASS object
df = pd.DataFrame(data)
# Use the plot METHOD
df.plot('x', 'y')
ในแบบฝึกหัดนี้ จะได้ใช้งาน คลาส และ เมธอด จาก แพ็กเกจ ยอดนิยมอย่าง numpy
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
หลักการวิศวกรรมซอฟต์แวร์ใน Python
คำแนะนำการฝึกหัด
- เติมคำสั่ง
importให้สมบูรณ์เพื่อโหลด แพ็กเกจnumpy - ใช้ คลาส
arrayของnumpyเพื่อกำหนดค่าให้arr - ใช้ เมธอด
sortของarrเพื่อเรียงลำดับอาร์เรย์numpy
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# import the numpy package
import ____ as np
# create an array class object
arr = np.____([8, 6, 7, 5, 3, 0, 9])
# use the sort method
arr.____()
# print the sorted array
print(arr)