Python進階之道

Python 和 JavaScript 在筆者看來是很相似的語言，本文歸納了 Python 的語言專屬特性。

語言專屬特性

推導式

列表推導式

even = [i for i in range(10) if not i % 2]
even
# [0, 2, 4, 6, 8]

字典推導式

SEIREI = [(0, 'takamiya mio'), (1, 'tobiichi origami'), (2, 'honjou nia'), (3, 'tokisaki kurumi'), (4, 'yoshino'), (5, 'itsuka kotori'), (6, 'hoshimiya mukuro'), (7, 'natsumi'), (8, 'yamai'), (9, 'izayoi miku'), (10, 'yatogami tohka')]
seirei_code = {seirei: code for code, seirei in SEIREI}
seirei_code
# {'takamiya mio': 0, 'tobiichi origami': 1, 'honjou nia': 2, 'tokisaki kurumi': 3, 'yoshino': 4, 'itsuka kotori': 5, 'hoshimiya mukuro': 6, 'natsumi': 7, 'yamai': 8, 'izayoi miku': 9, 'yatogami tohka': 10}
{code: seirei.upper() for seirei, code in seirei_code.items() if code > 6}
# {7: 'NATSUMI', 8: 'YAMAI', 9: 'IZAYOI MIKU', 10: 'YATOGAMI TOUKA'}

集合推導式

{x ** 2 for x in [1, 2, 2, 3, 3]}
# {1, 4, 9}

生成器表達式

even_sum_under_10 = sum(i for i in range(11) if not i % 2)
even_sum_under_10
# 30

解包

a, b = b, a
# 等價於 a, b = (b, a)

first, *rest = [1, 2, 3, 4]
first
# 1
rest
# [2, 3, 4]

filename, _ = 'eroge.exe'.split('.')
filename
# 'eroge'

星號運算符

數據容器的合併

l1 = ['kaguya', 'miyuki']
l2 = ['chika', 'ishigami']
[*l1, *l2]
# ['kaguya', 'miyuki', 'chika', 'ishigami']
d1 = {'name': 'rimuru'}
d2 = {'kind': 'slime'}
{**d1, **d2}
# {'name': 'rimuru', 'kind': 'slime'}

函數參數的打包與解包

# 打包
def foo(*args):
print(args)
foo(1, 2)
# (1, 2)
def bar(**kwargs):
print(kwargs)
bar(name='hayasaka', job='maid')
# {'name': 'hayasaka', 'job': 'maid'}
# 解包
t = (10, 3)
quotient, remainder = divmod(*t)
quotient
# 商：3
remainder
# 餘：1

裝飾器

import time
from functools import wraps
def clock(func):
@wraps(func) # 防止被裝飾函數的屬性被wrapper覆蓋
def wrapper(*args, **kwargs):
t0 = time.perf_counter()
result = func(*args, **kwargs) # 由於閉包，wrapper函數包含了自由變量func
elapsed = time.perf_counter() - t0
name = func.__name__
args = ', '.join(repr(arg) for arg in args)
kwargs = ', '.join(f'{k}={w}' for k, w in sorted(kwargs.items()))
all_args_str = ', '.join(astr for astr in [args_str, kwargs_str] if astr)
print(f'[{elapsed:.8f}s] {name}({all_args_str}) -> {result}')
return result
return wrapper # 返回內部函數，取代被裝飾的函數
@clock
def factorial(n: int) -> int:
return 1 if n < 2 else n * factorial(n-1)
factorial(5)
# [0.00000044s] factorial(1) -> 1
# [0.00011111s] factorial(2) -> 2
# [0.00022622s] factorial(3) -> 6
# [0.00030844s] factorial(4) -> 24
# [0.00042222s] factorial(5) -> 120
# 120

import time
from functools import wraps
DEFAULT_FMT = '[{elapsed:.8f}s] {name}({all_args_str}) -> {result}'
def clock(fmt=DEFAULT_FMT):
def decorate(func):
@wraps(func)
def wrapper(*args, **kwargs):
t0 = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - t0
name = func.__name__
args_str = ', '.join(repr(arg) for arg in args)
kwargs_str = ', '.join(f'{k}={w}' for k, w in sorted(kwargs.items()))
all_args_str = ', '.join(astr for astr in [args_str, kwargs_str] if astr)
print(fmt.format(**locals()))
return result
return wrapper
return decorate
@clock()
def factorial_default_fmt(n: int) -> int:
return 1 if n < 2 else n * factorial_default_fmt(n-1)
@clock('{name}: {elapsed}s')
def factorial_customed_fmt(n: int) -> int:
return 1 if n < 2 else n * factorial_customed_fmt(n-1)
factorial_default_fmt(3)
# [0.00000044s] factorial_default_fmt(1) -> 1
# [0.00009600s] factorial_default_fmt(2) -> 2
# [0.00018133s] factorial_default_fmt(3) -> 6
# 6
factorial_customed_fmt(3)
# factorial_customed_fmt: 4.444450496521313e-07s
# factorial_customed_fmt: 9.733346314533264e-05s
# factorial_customed_fmt: 0.0001831113553407704s
# 6

上下文管理器

# try:
#     f = open(input_path)
# finally:
#     f.close()
with open(input_path) as f:

# with open('file') as i:
from pathlib import Path

from contextlib import contextmanager
@contextmanager
def open_write(filename):
try:
f = open(filename, 'w')
yield f
finally:
f.close()
with open_write('onegai.txt') as f:
f.write('Dagakotowaru!')

多重繼承

MRO 是啥？Method Resolution Order（方法解析順序）

class A:
def __init__(self):
print('A')
class B(A):
def __init__(self):
print('enter B')
super().__init__()
print('leave B')
class C(A):
def __init__(self):
print('enter C')
super().__init__()
print('leave C')
class D(B, C):
pass
d = D()
# enter B
# enter C
# A
# leave C
# leave B
print(d.__class__.__mro__)
# (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

特殊方法

from math import hypot
class Vector2d:
# 限制允許綁定的屬性
__slots__ = ('__x', '__y')
# 實例創建
def __init__(self, x, y):
self.__x = float(x)
self.__y = float(y)
# 前雙下劃線是私有屬性，property裝飾是隻讀屬性
@property
def x(self):
return self.__x
@property
def y(self):
return self.__y
# 可迭代對象
def __iter__(self):
yield from (self.x, self.y)
# 字符串表示形式
def __repr__(self) -> str:
return f'{type(self).__name__}({self.x}, {self.y})'
# 數值轉換 - 絕對值
def __abs__(self) -> float:
return hypot(self.x, self.y)
# 數值轉換 - 布爾值
def __bool__(self) -> bool:
return bool(abs(self))
# 算術運算符 - 加
x = self.x + other.x
y = self.y + other.y
return Vector2d(x, y)
# 算術運算符 - 乘
def __mul__(self, scalar: float):
return Vector2d(self.x * scalar, self.y * scalar)
# 比較運算符 - 相等
def __eq__(self, other):
return tuple(self) == tuple(other)
# 可散列
def __hash__(self):
return hash(self.x) ^ hash(self.y)
v = Vector2d(3, 4)
# __slots__限制了允許綁定的屬性，只能是x或y
v.z = 1
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# AttributeError: 'Vector2d' object has no attribute 'z'
# 由於x屬性只讀，因此無法再次賦值
v.x = 1
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# AttributeError: can't set attribute
# iter(v) => v.__iter__()
x, y = v
# x為3, y為4
# repr(v) => v.__repr__()
v
# Vector2d(3, 4)
# abs(v) => v.__abs__()
abs(v)
# 5.0
# bool(v) => v.__bool__()
bool(v)
# True
# v1 + v2  => v1.__add__(v2)
v1 = Vector2d(1, 2)
v2 = Vector2d(3, 4)
v1 + v2
# Vector2d(4, 6)
# v * 3  => v.__mul__(3)
v * 3
# Vector2d(9, 12)
# v1 == v2 => v1.__eq__(v2)
v1 = Vector2d(1, 2)
v2 = Vector2d(1, 2)
v1 == v2
# True
# hash(v) => v.__hash__()
hash(v)
# 7
v1 = Vector2d(1, 2)
v2 = Vector2d(3, 4)
set([v1, v2])
# {Vector2d(1.0, 2.0), Vector2d(3.0, 4.0)}

from liay import liay
import reprlib
import math
import numbers
import string
from functools import reduce
from operator import xor
from itertools import zip_longest
import numbers
from fractions import Fraction as F
class Vector:
typecode = 'd'
shortcut_names = 'xyzt'
def __init__(self, components):
self._components = liay(self.typecode, components)
def __iter__(self):
return iter(self._components)
def __repr__(self):
components = reprlib.repr(self._components)
components = components[components.find('['):-1]
return f'{type(self).__name__}({components})'
def __str__(self):
return str(tuple(self))
def __eq__(self, other):
return tuple(self) == tuple(other)
def __bool__(self):
return bool(abs(self))
# 序列協議 - 獲取長度
def __len__(self):
return len(self._components)
# 序列協議 - 索引取值
def __getitem__(self, index):
cls = type(self)  # Vector
if isinstance(index, slice):  # 索引是slice對象，則返回Vector實例
return cls(self._components[index])
elif isinstance(index, numbers.Integral):  # 索引是整數類型，則返回_components中對應的數字
return self._components[index]
else:
raise TypeError(f'{cls.__name__} indices must be integers.')
# 屬性訪問，獲取分量的值
def __getattr__(self, name):
cls = type(self)
if len(name) == 1:
pos = cls.shortcut_names.find(name)
if 0 <= pos < len(self._components):
return self._components[pos]
raise AttributeError(f'{cls.__name__} has no attribute {name}')
# 屬性設置，給分量設值時會拋出異常，使向量是不可變的
def __setattr__(self, name, value):
cls = type(self)
if len(name) == 1:
if name in string.ascii_lowercase:
raise AttributeError(f"can't set attribute 'a' to 'z' in {cls.__name__}")
super().__setattr__(name, value)
# 比較所有分量，都相等才算兩向量相等
def __eq__(self, other):
return len(self) == len(other) and all(a == b for a, b in zip(self, other))
# 散列化
def __hash__(self):
hashes = map(hash, self._components)
return reduce(xor, hashes, 0)
# 絕對值
def __abs__(self):
return math.sqrt(sum(x ** 2 for x in self))
# 取正
def __pos__(self):
return Vector(self)
# 取負
def __neg__(self):
return Vector(-x for x in self)
# 加 (減法__sub__的實現與之類似，略)
try:
return Vector(a + b for a, b in zip_longest(self, other, fillvalue=0.0))
except TypeError:
return NotImplemented
return self + other
# 乘 (除法__truediv__的實現與之類似，略)
def __mul__(self, scalar):
return Vector(n * scalar for n in self) if isinstance(scalar, numbers.Real) else NotImplemented
# 反向乘
def __rmul__(self, scalar):
return self * scalar
# 中綴運算符@ - 點積
def __matmul__(self, other):
try:
return sum(a * b for a, b in zip(self, other))
except TypeError:
return NotImplemented
# 反向中綴運算符@
def __rmatmul__(self, other):
return self @ other
v = Vector(range(7))
v
# Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...])
v[1:3]
# Vector([1.0, 2.0])
v[-1]
# 6.0
v[1,3]
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "<stdin>", line 39, in __getitem__
# TypeError: Vector indices must be integers.
v.x, v.y, v.z
# (0.0, 1.0, 2.0)
v.x = 1
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
#   File "<stdin>", line 62, in __setattr__
# AttributeError: can't set attribute 'a' to 'z' in Vector
v1 = Vector((3, 4, 5))
v2 = Vector((6, 7))
v1 == v2
# False
set([v1, v2])
# {Vector([6.0, 7.0]), Vector([3.0, 4.0, 5.0])}
abs(v)
# 9.539392014169456
+v
# Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...])
-v
# Vector([-0.0, -1.0, -2.0, -3.0, -4.0, ...])
v1 + v2
# Vector([9.0, 11.0, 5.0])
v * 3
# Vector([0.0, 3.0, 6.0, 9.0, 12.0, ...])
v * F(1, 2)
# Vector([0.0, 0.5, 1.0, 1.5, 2.0, ...])
v1 @ v2
# 46.0

類方法和靜態方法

@classmethod 是類方法，它定義操作類的方法，也就是說會將類綁定給方法，而不是實例

@staticmethod 是靜態方法，啥都不綁定，一般用來給類綁定各種工具方法（不涉及對實例和類的操作）

class Post(models.Model):
STATUS_NORMAL = 1
STATUS_DELETE = 0
STATUS_DRAFT = 2
STATUS_ITEMS = (
(STATUS_NORMAL, '正常'),
(STATUS_DELETE, '刪除'),
(STATUS_DRAFT, '草稿'),
)
...
status = models.PositiveIntegerField(_("狀態"), choices=STATUS_ITEMS, default=STATUS_NORMAL)
...
@classmethod
def latest_posts(cls, limit=None):
queryset = cls.objects.filter(status=cls.STATUS_NORMAL).order_by('-created_time')
if limit:
queryset = queryset[:limit]
return queryset

描述符

set 和 get 代表存和取，因此描述符是一種對多個類屬性運用相同存取邏輯的一種方式

class Validator:
def __init__(self, storage_name):
self.storage_name = storage_name
def __set__(self, instance, value):
if not isinstance(value, int):
raise ValueError('Value must be an integer')
if value > 200:
raise ValueError('Value must be under 200')
class Person:
age = Validator('age')
def __init__(self, age):
self.age = age
person = Person(age=100)
person.age = 'young'
# Traceback (most recent call last):
# ValueError: Value must be an integer
person.age = 201
# Traceback (most recent call last):
# ValueError: Value must be under 200

元類

type(name, bases, dict) -> a new type

name 是新類的名稱，bases 是繼承的子類，dict 則是新類的屬性名與其對應值的字典

class A:
a = 1
def foo(self):
return self.a * 2
# 以上類的創建等價於
A = type('A', (object, ), {'a': 1, 'foo': lambda self: self.a * 2})

'alphardex'.__class__
# <class 'str'>
'alphardex'.__class__.__class__
# <class 'type'>

class UpperAttrMeta(type):
def __new__(cls, name, bases, attrs):
"""
__init__方法用來初始化對象並傳入參數

"""
upper_attrs = {k.upper() if not k.startswith('_') else k: v for k, v in attrs.items()}
return super().__new__(cls, name, bases, upper_attrs)
class Foo(metaclass=UpperAttrMeta):
name = 'alphardex'
__love = 'unknown'
f = Foo()
f.NAME
# 'alphardex'
f._Foo__love
# 'unknown'

class Person(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
p = Person(name='alphardex', age='24')
p.age
# 24

DOM的常用API速查表

JavaScript進階之道