🐍 Thuật Ngữ Python - Python-Specific Terms
Tóm tắt: Từ điển các thuật ngữ chuyên biệt của Python, bao gồm các khái niệm, cú pháp và tính năng độc đáo mà chỉ có trong Python hoặc được Python định nghĩa theo cách riêng.
🎯 Tại Sao Python Có Thuật Ngữ Riêng?
Python như một quốc gia có văn hóa riêng! 🏛️ Mỗi ngôn ngữ lập trình có những đặc trưng và thuật ngữ riêng. Hiểu được "ngôn ngữ Python" giúp bạn:
- Đọc tài liệu Python dễ dàng 📖
- Giao tiếp với Python developers 🤝
- Hiểu sâu triết lý của Python 🧘♂️
- Debug hiệu quả hơn 🔧
🐍 THUẬT NGỮ PYTHON THEO ABC
A
__all__
(All exports)
Giải thích đơn giản: Như danh sách "món ăn được phép mang đi"! 🍽️
__all__
định nghĩa những gì được "xuất khẩu" khi ai đó dùng from module import *
.
# file: math_utils.py
"""Module tính toán đơn giản."""
def add(a, b):
"""Hàm cộng công khai."""
return a + b
def subtract(a, b):
"""Hàm trừ công khai."""
return a - b
def _private_helper():
"""Hàm riêng tư, không nên export."""
return "This is private"
def _another_private():
"""Hàm riêng tư khác."""
return "Also private"
# Định nghĩa những gì được export
__all__ = ['add', 'subtract'] # Chỉ export 2 hàm này
# Khi ai đó dùng: from math_utils import *
# Họ chỉ có thể dùng add() và subtract()
# Không thể dùng _private_helper() và _another_private()
# Demo __all__
def demo_all_usage():
"""Demo cách __all__ hoạt động."""
# Giả lập việc import
print("=== DEMO __all__ ===")
print("Trong math_utils.py có:")
print("- add() ✅ (trong __all__)")
print("- subtract() ✅ (trong __all__)")
print("- _private_helper() ❌ (không trong __all__)")
print("- _another_private() ❌ (không trong __all__)")
print("\nKhi dùng: from math_utils import *")
print("Chỉ có thể dùng: add(), subtract()")
demo_all_usage()
Args và Kwargs
Giải thích đơn giản: Như "buffet" và "menu đặc biệt"! 🍤
*args
: Nhận nhiều arguments (như buffet - ăn bao nhiêu cũng được)- `kwargs: Nhận keyword arguments (như menu đặc biệt - gọi theo tên)
def flexible_function(*args, **kwargs):
"""Hàm linh hoạt nhận bất kỳ số lượng arguments nào."""
print("=== ARGS VÀ KWARGS DEMO ===")
# Xử lý args (positional arguments)
print(f"Positional arguments (*args): {args}")
print(f"Số lượng args: {len(args)}")
if args:
print("Chi tiết từng arg:")
for i, arg in enumerate(args):
print(f" arg[{i}]: {arg} (type: {type(arg).__name__})")
# Xử lý kwargs (keyword arguments)
print(f"\nKeyword arguments (**kwargs): {kwargs}")
print(f"Số lượng kwargs: {len(kwargs)}")
if kwargs:
print("Chi tiết từng kwarg:")
for key, value in kwargs.items():
print(f" {key} = {value} (type: {type(value).__name__})")
# Test với nhiều kiểu arguments
print("Test 1: Chỉ args")
flexible_function(1, "hello", [1, 2, 3])
print("\nTest 2: Chỉ kwargs")
flexible_function(name="An", age=20, grade=8.5)
print("\nTest 3: Cả args và kwargs")
flexible_function("Python", 3.9, True, language="Python", level="intermediate")
# Practical example: Student registration
def register_student(name, *subjects, **info):
"""Đăng ký học sinh với môn học và thông tin bổ sung."""
print(f"\n=== ĐĂNG KÝ HỌC SINH ===")
print(f"Tên: {name}")
# Subjects (args)
if subjects:
print(f"Môn học ({len(subjects)} môn):")
for subject in subjects:
print(f" - {subject}")
else:
print("Chưa đăng ký môn nào")
# Additional info (kwargs)
if info:
print("Thông tin bổ sung:")
for key, value in info.items():
print(f" {key}: {value}")
return {
'name': name,
'subjects': list(subjects),
'info': info
}
# Test student registration
student1 = register_student(
"Nguyễn Văn An", # name
"Toán", "Lý", "Hóa", # *subjects
age=18, city="Hà Nội", email="[email protected]" # **info
)
student2 = register_student(
"Trần Thị Bình",
"Văn", "Sử", "Địa", "Sinh",
age=17, phone="0123456789"
)
B
Built-in (Có sẵn)
Giải thích đơn giản: Như đồ dùng có sẵn trong nhà! 🏠
Built-in functions là những hàm "có sẵn" trong Python, không cần import gì cả.
def demo_builtin_functions():
"""Demo các built-in functions phổ biến."""
print("=== BUILT-IN FUNCTIONS DEMO ===")
# Dữ liệu test
numbers = [1, 5, 3, 9, 2, 8]
text = "Hello Python"
# 1. len() - Độ dài
print(f"len({numbers}) = {len(numbers)}")
print(f"len('{text}') = {len(text)}")
# 2. max(), min() - Lớn nhất, nhỏ nhất
print(f"max({numbers}) = {max(numbers)}")
print(f"min({numbers}) = {min(numbers)}")
# 3. sum() - Tổng
print(f"sum({numbers}) = {sum(numbers)}")
# 4. sorted() - Sắp xếp
print(f"sorted({numbers}) = {sorted(numbers)}")
print(f"sorted('{text}') = {sorted(text)}")
# 5. type() - Kiểu dữ liệu
print(f"type({numbers}) = {type(numbers).__name__}")
print(f"type('{text}') = {type(text).__name__}")
# 6. isinstance() - Kiểm tra kiểu
print(f"isinstance({numbers}, list) = {isinstance(numbers, list)}")
print(f"isinstance('{text}', str) = {isinstance(text, str)}")
# 7. range() - Dãy số
print(f"list(range(5)) = {list(range(5))}")
print(f"list(range(2, 8, 2)) = {list(range(2, 8, 2))}")
# 8. enumerate() - Đánh số thứ tự
print("enumerate(['a', 'b', 'c']):")
for i, letter in enumerate(['a', 'b', 'c']):
print(f" {i}: {letter}")
# 9. zip() - Ghép đôi
names = ["An", "Bình", "Cường"]
ages = [20, 19, 21]
print("zip(names, ages):")
for name, age in zip(names, ages):
print(f" {name}: {age} tuổi")
# Built-in constants
def demo_builtin_constants():
"""Demo các hằng số built-in."""
print("\n=== BUILT-IN CONSTANTS ===")
# Boolean constants
print(f"True: {True} (type: {type(True).__name__})")
print(f"False: {False} (type: {type(False).__name__})")
# None - giá trị "không có gì"
print(f"None: {None} (type: {type(None).__name__})")
# Ellipsis - dấu "..."
print(f"Ellipsis (...): {Ellipsis} (type: {type(Ellipsis).__name__})")
# NotImplemented - cho các phép toán chưa implement
print(f"NotImplemented: {NotImplemented}")
demo_builtin_functions()
demo_builtin_constants()
Bytecode (Mã byte)
Giải thích đơn giản: Như "ngôn ngữ trung gian"! 🔄
Python code được chuyển thành bytecode trước khi chạy, giống như phiên dịch từ tiếng Việt sang tiếng Anh rồi mới nói với người nước ngoài.
import dis
import py_compile
import os
def demo_bytecode():
"""Demo bytecode trong Python."""
print("=== BYTECODE DEMO ===")
# Hàm đơn giản để phân tích
def simple_function(x, y):
"""Hàm đơn giản cộng hai số."""
result = x + y
return result
# 1. Xem bytecode của function
print("Bytecode của simple_function:")
print("-" * 40)
dis.dis(simple_function)
# 2. Compile và tạo .pyc file
print(f"\n=== COMPILE TO BYTECODE ===")
# Tạo file Python
code = '''
def greet(name):
"""Hàm chào hỏi."""
message = f"Xin chào {name}!"
return message
if __name__ == "__main__":
print(greet("Python"))
'''
filename = "temp_demo.py"
with open(filename, 'w', encoding='utf-8') as f:
f.write(code)
# Compile thành bytecode
py_compile.compile(filename)
print(f"✅ Đã compile {filename} thành bytecode")
print("Tạo ra file .pyc trong __pycache__/")
# 3. Bytecode của string expression
print(f"\n=== BYTECODE CỦA EXPRESSIONS ===")
# Compile expression thành code object
expression = "x + y * 2"
code_obj = compile(expression, '<string>', 'eval')
print(f"Expression: {expression}")
print("Bytecode:")
dis.dis(code_obj)
# Cleanup
if os.path.exists(filename):
os.remove(filename)
# Remove __pycache__ directory
import shutil
if os.path.exists('__pycache__'):
shutil.rmtree('__pycache__')
# Demo code object
def demo_code_objects():
"""Demo Code Objects trong Python."""
print(f"\n=== CODE OBJECTS ===")
def sample_func(a, b=10, *args, **kwargs):
"""Sample function để phân tích."""
c = a + b
return c * 2
code = sample_func.__code__
print(f"Function name: {code.co_name}")
print(f"Filename: {code.co_filename}")
print(f"Line number: {code.co_firstlineno}")
print(f"Argument count: {code.co_argcount}")
print(f"Local variables: {code.co_varnames}")
print(f"Constants: {code.co_consts}")
print(f"Bytecode: {code.co_code[:20]}...") # First 20 bytes
demo_bytecode()
demo_code_objects()
C
Comprehension (Biểu thức rút gọn)
Giải thích đơn giản: Như "công thức nấu ăn một dòng"! 👨🍳
Comprehension cho phép tạo list, dict, set trong một dòng code, thay vì viết vòng lặp dài.
def demo_comprehensions():
"""Demo tất cả các loại comprehensions."""
print("=== COMPREHENSIONS DEMO ===")
# Dữ liệu test
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
students = [
{"name": "An", "age": 20, "grade": 8.5},
{"name": "Bình", "age": 19, "grade": 9.0},
{"name": "Cường", "age": 21, "grade": 7.5},
{"name": "Dung", "age": 20, "grade": 8.8}
]
print("=== 1. LIST COMPREHENSION ===")
# Cách truyền thống
squares_traditional = []
for num in numbers:
squares_traditional.append(num ** 2)
# List comprehension
squares_comp = [num ** 2 for num in numbers]
print(f"Số gốc: {numbers}")
print(f"Bình phương (traditional): {squares_traditional}")
print(f"Bình phương (comprehension): {squares_comp}")
# Với điều kiện
even_squares = [num ** 2 for num in numbers if num % 2 == 0]
print(f"Bình phương số chẵn: {even_squares}")
# Nested comprehension
matrix = [[i*j for j in range(1, 4)] for i in range(1, 4)]
print(f"Ma trận 3x3: {matrix}")
print(f"\n=== 2. DICT COMPREHENSION ===")
# Tạo dict từ list
number_squares = {num: num**2 for num in range(1, 6)}
print(f"Dict bình phương: {number_squares}")
# Từ students list
name_grades = {student["name"]: student["grade"] for student in students}
print(f"Tên-Điểm: {name_grades}")
# Với điều kiện
high_achievers = {
student["name"]: student["grade"]
for student in students
if student["grade"] >= 8.0
}
print(f"Học sinh giỏi: {high_achievers}")
print(f"\n=== 3. SET COMPREHENSION ===")
# Tạo set các độ tuổi
ages = {student["age"] for student in students}
print(f"Các độ tuổi: {ages}")
# Set bình phương số lẻ
odd_squares = {num**2 for num in numbers if num % 2 == 1}
print(f"Bình phương số lẻ: {odd_squares}")
print(f"\n=== 4. GENERATOR COMPREHENSION ===")
# Generator (lazy evaluation)
squares_gen = (num**2 for num in numbers)
print(f"Generator object: {squares_gen}")
print(f"Generator values: {list(squares_gen)}")
# Memory efficient cho big data
big_squares = (x**2 for x in range(1000000) if x % 1000 == 0)
first_10 = [next(big_squares) for _ in range(10)]
print(f"First 10 big squares: {first_10}")
def advanced_comprehensions():
"""Advanced comprehension examples."""
print(f"\n=== ADVANCED COMPREHENSIONS ===")
# Nested loops trong comprehension
colors = ['red', 'blue']
sizes = ['S', 'M', 'L']
# Tạo tất cả combinations
products = [f"{color}-{size}" for color in colors for size in sizes]
print(f"Products: {products}")
# Flatten nested list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for sublist in nested_list for item in sublist]
print(f"Nested: {nested_list}")
print(f"Flattened: {flattened}")
# Conditional expression trong comprehension
numbers = range(-5, 6)
abs_or_zero = [x if x >= 0 else 0 for x in numbers]
print(f"Numbers: {list(numbers)}")
print(f"Abs or zero: {abs_or_zero}")
# Multiple conditions
text = "Hello World Python Programming"
words = text.split()
long_words = [
word.upper()
for word in words
if len(word) > 5 and word.startswith('P')
]
print(f"Words: {words}")
print(f"Long words starting with P: {long_words}")
demo_comprehensions()
advanced_comprehensions()
CPython (Cài đặt C của Python)
Giải thích đơn giản: Như "động cơ" của Python! 🚗
CPython là cài đặt chính thức của Python, được viết bằng ngôn ngữ C. Đây là "động cơ" chạy code Python của bạn.
import sys
import platform
def demo_cpython_info():
"""Hiển thị thông tin về CPython implementation."""
print("=== CPYTHON INFORMATION ===")
# Python version và implementation
print(f"Python version: {sys.version}")
print(f"Python implementation: {platform.python_implementation()}")
print(f"Python compiler: {platform.python_compiler()}")
# System information
print(f"\nSystem: {platform.system()} {platform.release()}")
print(f"Architecture: {platform.architecture()}")
print(f"Machine: {platform.machine()}")
# Python paths
print(f"\nPython executable: {sys.executable}")
print(f"Python path: {sys.path[0]}")
# Memory and reference counting (CPython specific)
print(f"\n=== CPYTHON SPECIFICS ===")
# Reference counting example
import gc
class TestObject:
def __init__(self, name):
self.name = name
def __del__(self):
print(f"Object {self.name} is being deleted")
# Tạo object và check reference count
obj = TestObject("test")
print(f"Reference count of obj: {sys.getrefcount(obj)}")
# Tạo thêm reference
another_ref = obj
print(f"Reference count after another_ref: {sys.getrefcount(obj)}")
# Xóa reference
del another_ref
print(f"Reference count after del another_ref: {sys.getrefcount(obj)}")
# Garbage collection info
print(f"\nGarbage collection stats: {gc.get_stats()}")
print(f"GC counts: {gc.get_count()}")
# Demo CPython vs other implementations
def demo_python_implementations():
"""So sánh các implementation khác nhau."""
print(f"\n=== PYTHON IMPLEMENTATIONS ===")
implementations = {
'CPython': {
'description': 'Implementation chính thức, viết bằng C',
'pros': ['Tương thích tốt nhất', 'Nhiều thư viện C extensions'],
'cons': ['GIL làm chậm multithreading'],
'use_case': 'General purpose, most common'
},
'PyPy': {
'description': 'Implementation nhanh hơn với JIT compiler',
'pros': ['Nhanh hơn CPython 2-10x', 'Tương thích tốt'],
'cons': ['Startup chậm hơn', 'Memory usage cao hơn'],
'use_case': 'CPU-intensive applications'
},
'Jython': {
'description': 'Python chạy trên Java Virtual Machine',
'pros': ['Tích hợp với Java', 'Access Java libraries'],
'cons': ['Không support C extensions', 'Chậm hơn CPython'],
'use_case': 'Java integration'
},
'IronPython': {
'description': 'Python cho .NET Framework',
'pros': ['Tích hợp với .NET', 'Access .NET libraries'],
'cons': ['Chỉ cho Windows/.NET', 'Development chậm'],
'use_case': '.NET integration'
}
}
current_impl = platform.python_implementation()
print(f"Current implementation: {current_impl}")
for name, info in implementations.items():
print(f"\n{name}:")
print(f" Description: {info['description']}")
print(f" Pros: {', '.join(info['pros'])}")
print(f" Cons: {', '.join(info['cons'])}")
print(f" Use case: {info['use_case']}")
if name == current_impl:
print(" >>> BẠN ĐANG DÙNG IMPLEMENTATION NÀY! <<<")
demo_cpython_info()
demo_python_implementations()