蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行调用、绑定、返回与闭包

PYTHONPython 3.12legacy-function-lab.py
legacy-function-lab.py149 行
import json


def report(name, value):
    print(json.dumps([name, value], ensure_ascii=True))


def error_name(action):
    try:
        action()
    except (AttributeError, IndexError, KeyError, NameError, TypeError, ValueError) as error:
        return type(error).__name__
    return None


from contextlib import redirect_stdout
from io import StringIO


trace = []
def display_station(name):
    """Write one station label."""
    trace.append(name)
    print(f"站点 {name}")
    return


report("definition", [list(trace), display_station.__doc__, callable(display_station)])
capture = StringIO()
with redirect_stdout(capture):
    first = display_station("北站")
    second = display_station("南站")
report("reusable_output", [capture.getvalue().splitlines(), first, second, trace])

name = [4, 6]
original_name = name
name = "时刻"
report("name_rebinding", [type(original_name).__name__, type(name).__name__, original_name, name])

def rebind_count(count):
    count = 9
    return count

def add_record(records):
    records.append(["复核", 4])
    return records

def rebind_list(records):
    records = []
    return records


number = 4
report("integer_binding", [rebind_count(number), number])
report_list = ["北站"]
inside = add_record(report_list)
report("list_mutation", [inside is report_list, report_list, rebind_list(report_list)])

def station_record(name, level):
    return [name, level]


required = [station_record("东站", 4), error_name(lambda: station_record("东站")),
            error_name(lambda: station_record("东站", name="西站"))]
report("required_arguments", required)
keywords = [station_record(name="东站", level=4), station_record(level=4, name="东站")]
report("keyword_binding", keywords)

def with_default(name, level=4):
    return [name, level]

def shared_default(label, labels=[]):
    labels.append(label)
    return labels.copy()

def fresh_default(label, labels=None):
    if labels is None:
        labels = []
    labels.append(label)
    return labels


defaults = [with_default("东站"), with_default("东站", level=9),
            shared_default("东"), shared_default("西"),
            fresh_default("东"), fresh_default("西")]
report("default_binding", defaults)

def collect(primary, *extra, **labels):
    return [primary, type(extra).__name__, extra, labels]


variadic = [collect(4), collect(4,6,8), collect(4, status="就绪")]
report("variadic_binding", variadic)
report("parameter_cases", {
    "必备参数": required,
    "关键字参数": keywords,
    "默认参数": defaults,
    "不定长参数": variadic,
})

bonus = 3
def with_offset(offset):
    return lambda reading: reading + offset + bonus


one = with_offset(4)
two = with_offset(9)
report("lambda_scope", [(lambda left,right: left+right)(4,6),
                        (lambda left,right: left+right)(4,8),
                        one(2), two(2), sorted(["bbb","a","cc"], key=lambda word: len(word))])

def compute_total(left, right):
    result = left + right
    print(f"过程值 {result}")
    return result

def no_result():
    pass


calculation = StringIO()
with redirect_stdout(calculation):
    result = compute_total(6, 8)
report("return_results", [calculation.getvalue().splitlines(), result, no_result(), first])

total = 0
def total_locally(left, right):
    total = left + right
    return total

def assign_global(value):
    global total
    total = value

def counter():
    value = 0
    def increase():
        nonlocal value
        value += 1
        return value
    return increase


internal_total = total_locally(6,8)
before = total
assign_global(7)
tick = counter()
report("local_vs_global", [internal_total, before, total, tick(), tick()])
本例需在 Python 3.12 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Python 3.12

入口文件:projects/python-legacy-lab/legacy-function-lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 legacy-function-lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Python 3.12。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python2.x

课程关联工程包(登记关联44章) · 含当前章节或实例 · mbskycom202611a446.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习