project/
├── main.py # 入口
├── utils/
│ ├── __init__.py # 使目錄成為套件
│ └── math_ops.py
└── models/
├── __init__.py
└── user.py
# main.py
import utils.math_ops
from models.user import User
print(utils.math_ops.add(1, 2))
u = User('Alice', 30)
u.greet()
def scope_test():
spam = 'test spam'
def do_local():
spam = 'local spam' # 新區域變數
def do_nonlocal():
nonlocal spam # 綁定外層 (非全域) 變數
spam = 'nonlocal spam'
def do_global():
global spam # 綁定模組層級全域變數
spam = 'global spam'
do_local()
print('After local:', spam) # test spam
do_nonlocal()
print('After nonlocal:', spam) # nonlocal spam
do_global()
print('After global:', spam) # global spam
scope_test()
print('In global:', spam) # global spam
class Person:
# 類別屬性 (共享)
species = 'Human'
def __init__(self, name, age):
# 實例屬性 (各自獨立)
self.name = name
self.age = age
print('Constructor called')
def greet(self):
print(f'Hi, I am {self.name}, {self.age} years old.')
def __repr__(self):
return f'Person({self.name!r}, {self.age})'
p1 = Person('Wang', 20)
p1.greet()
print(p1) # 觸發 __repr__
Python 將實例方法的第一個參數慣例命名為 `self` (對應 C++/Java `this`)。呼叫 `p1.greet()` 實際轉為 `Person.greet(p1)`。
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age) # 呼叫父類建構子
self.student_id = student_id
def greet(self): # 覆寫
super().greet()
print(f' Student ID: {self.student_id}')
s = Student('Li', 19, 'S2024001')
s.greet()
class A: pass
class B: pass
class C(A, B): pass
print(C.__mro__) # (C, A, B, object)
# Python 3 皆為新式類 (隱含繼承 object),使用 C3 線性化演算法
Python 不支援傳統多載 (同名不同參數),改用**預設參數**或 `*args/**kwargs`:
def connect(host, port=80, timeout=5, **options):
...
connect('localhost')
connect('localhost', 8080)
connect('localhost', timeout=10, ssl=True)
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError('Radius cannot be negative')
self._radius = value
@property
def area(self):
return 3.14159 * self._radius ** 2
c = Circle(5)
print(c.area) # 唯讀屬性
c.radius = 10 # 觸發 setter 驗證
| 原則 | 說明 |
|---|---|
| 單一職責 | 一個模組/類別只做一件事 |
| 命名慣例 | 模組 `snake_case`、類別 `PascalCase`、常數 `UPPER_SNAKE` |
| 私有慣例 | `_single` 內部使用、`__double` 名稱修飾 (非真私有) |
| 文件字串 | 模組、類別、函數皆寫 `"""docstring"""` |
| 型別提示 | Python 3.5+ `def f(x: int) -> str:` 提升可讀度與靜態分析 |