Python
代码示例

↑  縮排示例：

def is_even(a: int) -> bool:
    """确定数a是否是偶数."""
    if a % 2 == 0:
        print('偶数!')
        return True
    print('奇数!')
    return False

# 参数比后续部份多一层缩进
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    # 可选的圆括号内后续行多一层缩进
    if (this_is_first_thing
            and that_is_second_thing):
        do_something()
    # 可选的圆括号内后续行不额外缩进
    elif (this_is_third_thing and
          that_is_fourth_thing):
        do_something_different()
# 参数相对行首缩进一层
spam = long_function_name(
    arg_one, arg_two,
    arg_three, arg_four)
# 参数按开括号界定垂直对齐
eggs = long_function_name(arg_one, arg_two,
                          arg_three, arg_four)
# 可选的闭括号位置
my_list = [
    1, 2, 3,
    4, 5, 6,
    ]
# 可选的闭括号位置
my_set = {
    1, 2, 3,
    4, 5, 6,
}
↑  采用了并行赋值的斐波那契数列函数示例：
def fib(n):  # 写出从第0项到第n项的Fibonacci系列
    a, b, i = 0, 1, 0 
    while i <= n:
        print(a, end=' ')
        a, b, i = b, a+b, i+1
    print()
↑  产生素数的惰性生成器的示例：

from itertools import count

def generate_primes(stop_at=0):
    if stop_at != 1:
        primes = [2]
        yield 2
    for n in count(3, 2):
        if 0 < stop_at < n:
            return # 引发StopIteration例外
        composite = False
        for p in primes:
            if not n % p:
                composite = True
                break
            elif p ** 2 > n:
                break
        if not composite:
            primes.append(n)
            yield n


上述函数的隐式迭代用例：

for i in generate_primes():  # 迭代于100以内所有素数上
    if i > 100:
        break
    print(i)

在生成器表达式中使用上述函数，定义了一个惰性的、巨大而并非无限的搜集的示例： 
from itertools import islice

primes_under_million = (i for i in generate_primes() if i < 1000000)
two_thousandth_prime = islice(primes_under_million, 1999, 2000) 
print(next(two_thousandth_prime))
↑  用生成器模拟协程示例：
def produce(n):
    try:
        for item in range(n):
            print(f'producing item {item} ->') 
            yield item
    except GeneratorExit:
        return

def consume():
    item = None
    try:
        while True:
            item = yield item
            print(f'consuming item {item} <-')
    except GeneratorExit:
        return

def main():
    r = []
    t1 = produce(10)
    t2 = consume()
    try:
        next(t2)
        while True:
            p = next(t1)
            r += [t2.send(p)]
    except StopIteration:
        t2.close()
    print(f'result items: {r}')

main()
↑  遵循EAFP（请求原谅比获得许可更容易）风格的例外处理示例：

f = None
try:
    f = open("aFileName", mode="w")
    f.write(could_make_error()) # 不存在could_make_error()则产生错误
except IOError as error:
    print(error)
    print("不能打开文件")
except:  # 捕获所有例外
    print("未预期的错误")
else:  # 在没有出现例外时执行
    print("文件写入完全成功")
finally:  # 清除行动，总是执行
    if f:
        f.close()
↑  使用with将文件作为资源来管理的示例：

from contextlib import contextmanager
@contextmanager
def opened(filename, mode="r"):
    try:
        f = open(filename, mode)
    except IOError as error:
        print(error)
        yield None
    else:
        try:
            yield f
        finally:
            f.close()

with opened("aFileName", mode="w") as f:
    try:
        f.write(could_make_error()) # 不存在could_make_error()则产生错误
    except AttributeError:
        print("不能打开文件")
    except:  # 捕获所有例外
        print("未预期的错误")
    else:  # 在没有出现例外时执行
        print("文件写入完全成功")
↑  原生的协程示例：
import asyncio
import random

async def produce(queue, n):
    for item in range(n):
        # 生产一个项目，使用sleep模拟I/O操作
        print(f'producing item {item} ->') 
        await asyncio.sleep(random.random())
        # 将项目放入队列
        await queue.put(item)
    # 指示生产完毕
    await queue.put(None)

async def consume(queue):
    while True:
        # 等待来自生产者的项目
        item = await queue.get()
        if item is None:
            break
        # 消费这个项目，使用sleep模拟I/O操作
        print(f'consuming item {item} <-')
        await asyncio.sleep(random.random()) 

async def main():
    queue = asyncio.Queue()
    task1 = asyncio.create_task(produce(queue, 10))
    task2 = asyncio.create_task(consume(queue))
    await task1
    await task2

asyncio.run(main())
↑  局部变量示例：
>>> def spam():
...     print(a)
... 
>>> a = 10
>>> spam()
10
>>> def spam():
...     a = 100
...     print(a)
... 
>>> spam()
100
>>> a
10
>>> def spam():
...     a *= 10
...     print(a)
... 
>>> spam()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in spam
UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
↑  全局变量示例：
>>> def spam():
...     global a
...     a *= 10
...     print(a)
... 
>>> a = 10
>>> spam()
100
>>> a
100
>>> def spam():
...     def eggs():
...         print(a)
...     global a
...     eggs()
... 
>>> a = 10
>>> spam()
10
>>> def spam():
...     def eggs():
...         a *= 10
...         print(a)
...     global a
...     eggs()
... 
>>> spam()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in spam
  File "<stdin>", line 3, in eggs
UnboundLocalError: cannot access local variable 'a' where it is not associated with a value
↑  非局部变量示例：
>>> def spam():
...     def eggs():
...         nonlocal a
...         a *= 10
...         print(a)
...     a = 10
...     eggs()
... 
>>> spam()
100
>>> def spam():
...     def eggs():
...         nonlocal a
...         a *= 10
...         print(a)
...     global a
...     eggs()
... 
  File "<stdin>", line 3
SyntaxError: no binding for nonlocal 'a' found
↑  序列解包、可迭代解包和字典解包示例：
>>> a = [1, 2, 3]; b = [4, 5]
>>> i, j, k = a
>>> print(i, j, k)
1 2 3
>>> c = [*a, b]
>>> c
[1, 2, 3, [4, 5]]
>>> d = {*a, *b}
>>> d
{1, 2, 3, 4, 5}
>>> e = (*a, *b)
>>> e
(1, 2, 3, 4, 5)
>>> f = {'as':1, 'bs':2 }; g = {'cs':3, 'ds':4}
>>> h = {**f, **g}
>>> h
{'as': 1, 'bs': 2, 'cs': 3, 'ds': 4}
↑  列表的推导式示例。比如：

>>> [x + 3 for x in range(4)]
[3, 4, 5, 6]

快速排序算法可以优雅的（尽管不高效的）使用列表推导式表达为：

def qsort(L):
    if L == []:
        return []
    pivot = L[0]
    return (qsort([x for x in L[1:] if x < pivot]) +
            [pivot] +
            qsort([x for x in L[1:] if x >= pivot]))
↑  生成器表达式示例。比如：

>>> sum(x * x for x in range(10))
285
>>> dict((n, n*n) for n in range(5))
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>>> set(n*n for n in range(5))
{0, 1, 4, 9, 16}
↑  字典推导式{expr1: expr2 for k, v in d}，等价于：
result={}
for k, v in d.items():
    result[expr1]=expr2
return result

>>> {x: x + 3 for x in range(4)}
{0: 3, 1: 4, 2: 5, 3: 6}

集合推导式{expr1 for x in stuff}，等价于：
result = set()
for x in stuff:
    result.add(expr1)
return result

>>> {x + 3 for x in range(4)}
{3, 4, 5, 6}
↑  下面几个判断语句为真，表示列表分片结果符合预期：
>>> nums = [1, 3, 5, 7, 8, 13, 20]
>>> nums[2:5] == [5, 7, 8] #从下标为2的元素切割到下标为5的元素，但不包含下标为5的元素。
True
>>> nums[1:] == [3, 5, 7, 8, 13, 20] #切割到最后一个元素。
True
>>> nums[:-3] == [1, 3, 5, 7] #从最开始的元素一直切割到倒数第3个元素。
True
>>> nums[:] == [1, 3, 5, 7, 8, 13, 20] #返回所有元素。改变新的列表不会影响到nums。
True
>>> nums[1:5:2] == [3, 7] #从下标为1的元素切割到下标为5的元素，但不包含下标为5的元素，且步长为2。
True
↑  匿名函数示例：
>>> from functools import reduce
>>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 
15
>>> fac = lambda n: (1 if n<2 else n*fac(n-1))
>>> fac(5)
120
>>> [*map(fac, [1, 2, 3, 4, 5])]
[1, 2, 6, 24, 120]

不动点组合子示例：
>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> Y(fac)(5)
120
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> Y(fib)(6)
8
>>> [*map((lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))))(lambda f: lambda n: (1 if n<2 else n*f(n-1))), [1, 2, 3, 4, 5])]
[1, 2, 6, 24, 120]

上述Y组合子代码源出自.   [2020-10-21]. （原始内容存档于2021-01-11）. 其原理可参见.   [2020-10-21]. （原始内容存档于2020-11-12）.
↑  多行字符串文字带有字符串插值（英语：）（使用了format方法）的示例：
print("""亲爱的{recipient},

我希望你离开Sunnydale并永不返回.

不是很爱你的,
{sender}
""".format(sender="吸血鬼猎人Buffy", recipient="Spike"))
↑  原始字符串的示例：
>>> # Windows路径，即使是原始字符串也不能结束于反斜杠
>>> r"C:\Spam\Eggs\Ham\"
  File "<stdin>", line 1
    r"C:\Spam\Eggs\Ham\"
                       ^
SyntaxError: EOL while scanning string literal
>>> dos_path = r"C:\Spam\Eggs\Ham\ " # 通过增加尾随的空格
>>> dos_path.rstrip()              # 并接着移除它来避免错误
'C:\\Spam\\Eggs\\Ham\\'
>>> quoted_dos_path = r'"{}"'.format(dos_path)
>>> quoted_dos_path
'"C:\\Spam\\Eggs\\Ham\\ "'
>>> # 匹配具有可能的反斜杠引述的引述字符串的正则表达式
>>> import re
>>> re.match(r'"(([^"\\]|\\.)*)"', quoted_dos_path).group(1).rstrip()
'C:\\Spam\\Eggs\\Ham\\'
>>> code = 'spam(2, eggs)'
>>> # 反转有二个参数的函数调用的两个实际参数
>>> re.sub(r'\(([^,]*),\s*([^,]*)\)', r'(\2, \1)', code)
'spam(eggs, 2)'
>>> # 注意如果实际参数中有圆括号或逗号则上例无效。
↑  字符串文字串接示例：

>>> print("hello " 'world')
hello world
>>> str1="hello "; str2='world'
>>> print(str1 + str2)
hello world
↑  格式化字符串的示例，例如下列命令行echo命令：
num="3"; printer="HP Laserjet"
echo "I just printed ${num} pages to the printer ${printer}"


等价于如下Python中的任何一种print函数调用：
num = 3; printer="HP Laserjet"
print(f"I just printed {num} pages to the printer {printer}")

print("I just printed {} pages to the printer {}".format(num, printer))
print("I just printed {0} pages to the printer {1}".format(num, printer))
print("I just printed {num} pages to the printer {printer}".format(num=num, printer=printer))

print("I just printed %s pages to the printer %s" % (num, printer))
print("I just printed %(num)s pages to the printer %(printer)s" % {"num": num, "printer": printer})
↑  词法闭包的例子：
def f(x):
    def g(y):
        return x + y
    return g  # 返回一个闭包。

h = lambda x: lambda y: x + y

# 将指定闭包赋值给变量。
a = f(1)
b = h(1)
c = f(2)
# 使用存储在变量中的闭包。
assert a(5) == 6
assert b(5) == 6
assert c(5) == 7
# 使用闭包而不事先把它们绑定到变量。
assert f(1)(5) == 6  # f(1)是个闭包。
assert h(1)(5) == 6  # h(1)是个闭包。
assert f(2)(5) == 7  # f(2)是个闭包。
↑  函数的形式参数缺省值的持久性示例：
>>> def f(a, L=[]):
...     L.append(a)
...     return L
... 
>>> print(f(1))
[1]
>>> print(f(2))
[1, 2]
>>> print(f(3))
[1, 2, 3]
↑  函数的形实参数二者结合示例。例如：
>>> def spam(a):
...     a.append('LovelySpam')
...     
>>> def eggs(b):
...     b=100 #实际上是重新绑定了另一个整型对象100
... 
>>> a=[]
>>> b=10
>>> spam(a)
>>> eggs(b)
>>> print(a)
['LovelySpam']
>>> print(b)
10
↑  函数的形式参数缺省值的定义示例：
>>> from inspect import getfullargspec
>>> def func(p1, /, p2, p3="x", *, p4): pass
... 
>>> getfullargspec(func)
FullArgSpec(args=['p1', 'p2', 'p3'], varargs=None, varkw=None, defaults=('x',), kwonlyargs=['p4'], kwonlydefaults=None, annotations={})
↑  函数的可变参数的定义示例：
>>> from inspect import getfullargspec
>>> def func(p1, /, p2, *args, p3, **kwargs): pass
... 
>>> getfullargspec(func)
FullArgSpec(args=['p1', 'p2'], varargs='args', varkw='kwargs', defaults=None, kwonlyargs=['p3'], kwonlydefaults=None, annotations={})
↑  定义修饰器的示例：

def viking_chorus(myfunc):
    def inner_func(*args, **kwargs):
        for i in range(3):
            myfunc(*args, **kwargs)
    return inner_func


调用修饰器的示例：

@viking_chorus    
def menu_item(*args):
    print(", ".join(args)+", and spam")


等价于：

def menu_item(*args):
    print(", ".join(args)+", and spam")

menu_item = viking_chorus(menu_item)

viking_chorus修饰后的menu_item将原来定义运行3次：
>>> menu_item("egg","bacon")
egg, bacon, and spam
egg, bacon, and spam
egg, bacon, and spam
↑  修饰器工厂示例，这里的favourite_colour接受一个实际参数，并返回一个修饰器：

def favourite_colour(colour):
    def decorator(func):
        def wrapper(*args, **kwargs):
            print(f"My favourite colour is {colour}.")
            func(*args, **kwargs)
        return wrapper
    return decorator

def invincible(func):
    def wrapper(*args, **kwargs):
        print("I'm invincible!")
        func(*args, **kwargs)
    return wrapper


使用毗连的修饰符链接修饰器示例：

@invincible
@favourite_colour("blue")
def black_knight():
    print("None shall pass.")


使用中间变量链接修饰器示例：

blue_decorator = favourite_colour("blue")
decorated_by_blue = blue_decorator(black_knight)
black_knight = invincible(decorated_by_blue)


它们等价于：

black_knight = invincible(favourite_colour("blue")(black_knight))

black_knight（英语：）()结果为：

>>> black_knight()
I'm invincible!
My favourite colour is blue.
None shall pass.
↑  调用函数使用帮助信息示例。比如：

>>> def randint(a, b):
...     "Return random integer in range [a, b], including both end points."
...
>>> help(randint)
Help on function randint in module __main__:   

randint(a, b)
    Return random integer in range [a, b], including both end points.
↑  如下这样给参数增加类型标注的提示信息：
>>> def greeting(name: str) -> str:
...     return 'Hello ' + name
... 
>>> greeting.__annotations__
{'name': <class 'str'>, 'return': <class 'str'>}
↑  对象的方法示例：

>>> class Fish(object):
...     hungry = True
...     def eat(self, food):
...         if food is not None:
...             self.hungry=False
... 
>>> def status(self):
...     print("Hungray!" if self.hungry else "Not hungray!")
... 
>>> e = Fish()
>>> status(e)
Hungray!
>>> Fish.hungry = False
>>> from types import MethodType
>>> e.status = MethodType(status, e)
>>> e.status()
Not hungray!
>>> Fish.hungry = True
>>> Fish.status = status
>>> f = Fish()
>>> Fish.status(f)
Hungray!
>>> f.eat("earthworm")
>>> f.status()
Not hungray!
↑  特殊方法和子类调用超类方法的例子： 

>>> class Thought(object):
...     cls_name = "类型Thought"
...     def __init_subclass__(cls):
...         cls.cls_name = "类型Thought的子类型"
...     def __init__(self, *args, **kwargs):
...         print(f"我是{type(self).cls_name}的新对象!")
...         if len(args) != 0 or len(kwargs) != 0:
...             print(f"init: nargs={len(args)}, nkwargs={len(kwargs)}")
...         self.notion = "我觉得我在平行宇宙中把车停歪了."
...     def message(self, *args):
...         print(self.notion)
...         if len(args) != 0:
...             print("\n".join(args))
... 
>>> class Advice(Thought):
...     def message(self):
...         super().message("警告: 日历里的日期比它们看起来更近!")
... 
>>> t = Thought()
我是类型Thought的新对象!
>>> t.message()
我觉得我在平行宇宙中把车停歪了.
>>> a = Advice()
我是类型Thought的子类型的新对象!
>>> a.message()
我觉得我在平行宇宙中把车停歪了.
警告: 日历里的日期比它们看起来更近!
>>> # 内省一下:
>>> [*super.__dict__]
['__new__', '__repr__', '__getattribute__', '__get__', '__init__', '__thisclass__', '__self__', '__self_class__', '__doc__']
>>> [*super(Advice).__thisclass__.__dict__]
['__module__', 'message', '__doc__', 'cls_name']
>>> super(Advice).__thisclass__.__dict__['cls_name']
'类型Thought的子类型'
>>> [*super(Advice, a).__self__.__dict__]
['notion']
>>> super(Advice, a).__self_class__.__dict__['cls_name']
'类型Thought的子类型'
>>> super(Advice, a).message()
我觉得我在平行宇宙中把车停歪了.
>>> super(Advice).__get__(a).message()
我觉得我在平行宇宙中把车停歪了.
↑  在类中采用数据描述器的示例：
>>> class RevealAccess:
...     """正常的设置和返回值的数据描述器，
...        它还打印记录这次访问的一个消息。
...     """
...     def __init__(self, initval=None, name='var'):
...         self.val = initval
...         self.name = name
...     def __get__(self, obj, objtype):
...         print('Retrieving', self.name)
...         return self.val
...     def __set__(self, obj, val):
...         print('Updating', self.name)
...         self.val = val
... 
>>> class MyClass:
...     x = RevealAccess(10, 'var "x"')
...     y = 5
...
>>> m = MyClass()
>>> m.x
Retrieving var "x"
10
>>> vars(m)
{}
>>> MyClass.__dict__['x'].val
10
>>> m.x = 20
Updating var "x"
>>> vars(m)
{}
>>> MyClass.__dict__['x'].val
20
>>> m.y
5
>>> vars(m)
{}
>>> m.y = 5
>>> vars(m)
{'y': 5}
↑  特殊方法、类方法和静态方法（__new__()）示例：
>>> from weakref import WeakValueDictionary
>>> class D:
...     _template = {}
...     _obj_dict = WeakValueDictionary()
...     def __new__(cls, *args, **kwargs):
...         obj = super(D, cls).__new__(cls)
...         cls._obj_dict[id(obj)] = obj
...         return obj
...     @classmethod
...     def load(cls, dict):
...         cls._template.update(dict)
...     @classmethod
...     def create(cls, *args, **kwargs):
...         return cls(cls._template, *args, **kwargs)
...     @classmethod
...     def count(cls):
...         return len(cls._obj_dict)
...     def __init__(self, dict={}, /, *args, **kwargs):
...         self.__dict__.update(dict)
...         self.__dict__.update(kwargs)
...     def __call__(self, *args, **kwargs):
...         self.__dict__.update(kwargs)
...         return self.__dict__.copy()
...     def __len__(self):
...         return len(self.__dict__)
...     def __getitem__(self, key):
...         return self.__dict__[key]
...     def __setitem__(self, key, value):
...         self.__dict__[key] = value
... 
>>> a = {'ak': 1, 'bk': 2, 'ck': 3}
>>> d = D(a, dk=4)
>>> d()
{'ak': 1, 'bk': 2, 'ck': 3, 'dk': 4}
>>> D.load(a)
>>> e = D.create(ck=4)
>>> e()
{'ak': 1, 'bk': 2, 'ck': 4}
>>> f = D(ak=1, bk=2)
>>> f(ck=3)
{'ak': 1, 'bk': 2, 'ck': 3}
>>> f['ak']
1
>>> f['ak'] = 5
>>> f()
{'ak': 5, 'bk': 2, 'ck': 3}
>>> len(f)
3
>>> D.count()
3
>>> del f
>>> D.count()
2
>>> d.__weakref__ in D._obj_dict.valuerefs()
True
↑  在类中调用property()的例子：
>>> class C:
...     def __init__(self):
...         self.__x = None
...     def getx(self):
...         return self.__x
...     def setx(self, value):
...         self.__x = value
...     def delx(self):
...         del self.__x
...     x = property(getx, setx, delx, "I'm the 'x' property.")
... 
>>> c = C()
>>> vars(c)
{'_C__x': None}
>>> {*C.__dict__}
{'__init__', 'setx', '__weakref__', 'delx', 'x', 'getx', '__doc__', '__module__', '__dict__'}


上述代码可以采用修饰符进一步的书写为：

>>> class C:
...     def __init__(self):
...         self.__x = None
...     @property
...     def x(self):
...         """I'm the 'x' property."""
...         return self.__x
...     @x.setter
...     def x(self, value):
...         self.__x = value
...     @x.deleter
...     def x(self):
...         del self.__x
... 
>>> c = C()
>>> vars(c)
{'_C__x': None}
>>> {*C.__dict__}
{'__init__', '__weakref__', 'x', '__doc__', '__module__', '__dict__'}
↑  
建立列表的特殊语法示例：
a_list = [1, 2, 3, 'a dog']

采用正常的对象创建方式的示例：
a_second_list = list()
a_second_list.append(4)
a_second_list.append(5)

建立元组的特殊语法示例：
a_tuple = 1, 2, 3, 'four'

建立集合的特殊语法示例：
some_set = {0, (), False}

建立字典的特殊语法示例：
a_dictionary = {'key 1': 'value 1', 2: 3, 4: []}
↑  
两个类及元类等的实例关系（蓝色连接）与继承关系（绿色连接）示意图：


 


r = object
c = type
class M(c): pass

class A(metaclass=M): pass

class B(A): pass

b = B()



>>> type(b)
<class '__main__.B'>
>>> print(type(B), B.__bases__)
<class '__main__.M'> (<class '__main__.A'>,)
>>> print(type(A), A.__bases__)
<class '__main__.M'> (<class 'object'>,)
>>> print(type(M), M.__bases__)
<class 'type'> (<class 'type'>,)
>>> print(type(c), c.__bases__)
<class 'type'> (<class 'object'>,)
>>> print(type(r), r.__bases__)
<class 'type'> ()
↑  数学运算示例。比如：

>>> def mean(seq):
...     return sum(seq) / len(seq)
... 
>>> mean([3, 4])
3.5
>>> import math
>>> print(math.sin(math.pi/2))
1.0