เรียน Python เพราะ AI แต่ดันติดใจเพราะฟีเจอร์เหล่านี้
1. Everything is an Object จริงๆ
ใน Python แม้แต่ function ก็เก็บใส่ตัวแปร ส่งเป็น parameter หรือคืนค่าจาก function ได้
def hello(name):
return f"Hello {name}"
f = hello
print(f("Bob"))
ภาษาอื่นเดี๋ยวนี้ก็ทำได้ แต่ Python ทำมาตั้งแต่โบราณและใช้เป็นเรื่องปกติ
2. Decorator = แก้พฤติกรรมฟังก์ชันโดยไม่แตะโค้ดเดิม
def log(func):
def wrapper(*args, **kwargs):
print("calling...")
return func(*args, **kwargs)
return wrapper
@log
def add(a, b):
return a + b
เรียก
add(1, 2)
จะ log อัตโนมัติ
Framework ดังๆ อย่าง
- FastAPI
- Flask
- Django
ใช้ decorator หนักมาก
3. Generator (yield)
ถือเป็นอาวุธลับของ Python แบ่งข้อมูลมหาศาลเป็น Pagination ทำให้ไม่ต้อง load ทั้งหมด โดยเขียนแค่เนี้ย! เยี่ยมจริงๆ
def count():
i = 0
while True:
yield i
i += 1
ใช้ได้แบบ
for x in count():
print(x)
โดยไม่กิน RAM เพิ่ม
หลายคนพอเข้าใจ yield แล้วจะเริ่มเขียนโค้ดคนละแบบเลย
4. List Comprehension
อันนี้สุดยอดการสร้าง List แบบ โอ้ววว คิดได้ไง กระชับดี
จากเดิมที่ต้องเขียนแบบนี้
result = []
for x in nums:
result.append(x * 2)
เหลือ
result = [x * 2 for x in nums]
กรองด้วยก็ได้
result = [x for x in nums if x % 2 == 0]
อ่านแล้วเหมือนภาษาอังกฤษ
5. Slicing
อันนี้คน Python ติดหนัก เพราะซอย List แบ่งมาใช้แบบสั้นและยืดหยุ่นมาก ในรูปแบบ [Start:End:Step]
arr[1:5]
arr[:10]
arr[-3:]
arr[::-1]
กลับลำดับทั้ง list โดยระบุ Direction ของ Step ด้วยเครื่องหมายลบก็ได้
arr[::-1]
สั้นกว่าหลายภาษาเยอะ
6. Multiple Return Values
def get_user():
return "Bob", 20
รับค่าได้เป็น Tuple หรือ List ที่เปลี่ยนแปลงค่าไม่ได้
name, age = get_user()
ไม่ต้องสร้าง class
ไม่ต้องสร้าง struct
7. Dynamic Typing ที่ฉลาด
x = 10
x = "hello"
x = [1,2,3]
เปลี่ยนชนิดได้ทันที
ข้อเสียก็มี แต่ตอนทำ prototype หรือ AI workflow เร็วมาก
8. Duck Typing
Python สนใจ "ทำอะไรได้" มากกว่า "เป็นอะไร"
class Dog:
def speak(self):
print("woof")
class Cat:
def speak(self):
print("meow")
def make_sound(animal):
animal.speak()
ไม่ต้อง implement interface
แค่มี method นั้นก็พอ ใครเบื่อตอนปั้น Interface ยกมือขึ้น 555
9. Magic Methods
สร้าง operator ของตัวเองได้
class Money:
def __init__(self, amount):
self.amount = amount
def __add__(self, other):
return Money(self.amount + other.amount)
แล้วใช้
a + b
เหมือน type built-in อันนี้เหมือนใน C++ เลย
10. Context Manager
with open("data.txt") as f:
data = f.read()
ไม่ต้อง
try:
...
finally:
f.close()
และเราสร้างเองได้ด้วยการ Implement Dunder methods
class MyContext:
def __enter__(self):
print("start")
def __exit__(self, *args):
print("end")
11. Introspection
Python สามารถสำรวจตัวเองได้
dir(obj)
type(obj)
hasattr(obj, "run")
getattr(obj, "run")
หรือแม้แต่
import inspect
inspect.signature(func)
ดู parameter ของ function ได้ตอน runtime
นี่คือเหตุผลที่ Framework ต่างๆ สร้างของเจ๋งๆ ได้ง่าย
12. Metaprogramming
Class สร้าง class ได้
MyClass = type(
"MyClass",
(),
{"x": 123}
)
หรือใช้ metaclass
class MyMeta(type):
pass
หากอยากกำหนด Spec
13. Dataclass
จาก
class User:
def __init__(self, name, age):
self.name = name
self.age = age
เหลือ
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
ได้ constructor, repr, equality ให้ฟรี
14. REPL Culture
Python ถูกออกแบบให้ทดลองได้ทันที
python
>>>
หรือ
ipython
หรือ หากจะรันแบบแยกส่วน อันนี้ Advance มากๆ คือ Debug ง่ายเลย เพราะไม่ต้องรันใหม่ทั้งหมด
jupyter notebook
วงการ AI และ Data Science โตได้ส่วนหนึ่งเพราะจุดนี้
15. Batteries Included
ติดตั้ง Python แล้วได้
- json
- sqlite3
- http.server
- csv
- xml
- asyncio
- threading
- multiprocessing
- pathlib
- unittest
แทบไม่ต้องหา library เพิ่ม
16. ฟีเจอร์ที่คนติดหนักที่สุด: "เขียน Framework เองได้"
หลังจากเข้าใจ
- decorator
- introspection
- getattr
- metaclass
- annotations
คุณจะเริ่มสร้างของแบบนี้ได้
@route("/hello")
def hello():
return "world"
หรือ
@intent("เปิดไฟ")
def turn_on_light():
...
คือออกแบบ Framework ที่ Config ง่ายๆมาใช้เองเลย
10 ฟีเจอร์ที่ทำให้คนไม่ค่อยอยากกลับไปเขียนภาษาเดิม
ถ้าจัดอันดับจากประสบการณ์ของคนจำนวนมาก
-
yield - decorator
- list comprehension
- slicing
- dataclass
- duck typing
- introspection
- REPL/Jupyter
- ecosystem AI
- เขียน DSL และ framework เองได้ง่ายมาก
หลายคนเริ่มจาก "Python มันช้า" แต่พอใช้ไปสักพักจะพบว่าจุดแข็งจริงๆ คือ "มันทำให้ไอเดียกลายเป็นโค้ดได้เร็วผิดปกติ" ซึ่งเป็นเหตุผลว่าทำไมงาน AI, Automation, Data Science และแม้แต่ Raspberry Pi ถึงมีคนเลือก Python เยอะมาก แม้จะรู้ว่าภาษาอื่นรันเร็วกว่าอยู่แล้วก็ตาม।
ความคิดเห็น
แสดงความคิดเห็น