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

运行离线 Python 校验:Kotlin 类委托、prop$delegate/provideDelegate、lazy 模式与标准委托

PYTHONWindows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。explore-delegated.py
explore-delegated.py266 行
"""Offline Kotlin 2.x semantic verifier for Chapter 27: Delegation."""
import json

VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"


def case_class_delegation_and_override():
    class BaseImpl:
        def __init__(self, x: int):
            self._x = x

        def print_val(self) -> str:
            return f"BaseImpl: {self._x}"

        def name(self) -> str:
            return "BaseImpl"

    class Derived:
        def __init__(self, delegate: BaseImpl):
            self._delegate = delegate

        def print_val(self) -> str:
            return self._delegate.print_val()

        def name(self) -> str:
            return "Derived"

    d = Derived(BaseImpl(10))
    actual = {"delegated_print": d.print_val(), "overridden_name": d.name()}
    expected = {"delegated_print": "BaseImpl: 10", "overridden_name": "Derived"}
    return {
        "name": "class_delegation_and_override",
        "summary": "Verify class delegation (by b) forwarding and selective method override in Derived",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_custom_property_delegate_and_provide_delegate():
    log = []

    class CustomDelegate:
        def get_value(self, this_ref, prop_name: str) -> str:
            return f"{this_ref} 读取了属性 {prop_name}"

        def set_value(self, this_ref, prop_name: str, value: str) -> None:
            log.append(f"{this_ref} 的 {prop_name} 被赋值为 {value}")

    class Example:
        def __init__(self):
            self._p_delegate = CustomDelegate()

        def __str__(self) -> str:
            return "Example"

        @property
        def p(self) -> str:
            return self._p_delegate.get_value(self, "p")

        @p.setter
        def p(self, value: str) -> None:
            self._p_delegate.set_value(self, "p", value)

    e = Example()
    read_msg = e.p
    e.p = "KOTLIN"

    # provideDelegate binding-time check
    def provide_delegate(value: str, allowed_name: str, actual_prop_name: str):
        if actual_prop_name != allowed_name:
            raise ValueError(f"属性名必须是 {allowed_name},实际是 {actual_prop_name}")
        return lambda: value

    ok_getter = provide_delegate("蓝色天空", "name", "name")
    bad_err = None
    try:
        provide_delegate("蓝色天空", "name", "siteName")
    except ValueError as exc:
        bad_err = str(exc)

    actual = {
        "get_result": read_msg,
        "set_log": log,
        "provide_delegate_ok": ok_getter(),
        "provide_delegate_err": bad_err,
        "backing_field_pattern": "prop$delegate",
    }
    expected = {
        "get_result": "Example 读取了属性 p",
        "set_log": ["Example 的 p 被赋值为 KOTLIN"],
        "provide_delegate_ok": "蓝色天空",
        "provide_delegate_err": "属性名必须是 name,实际是 siteName",
        "backing_field_pattern": "prop$delegate",
    }
    return {
        "name": "custom_property_delegate_and_provide_delegate",
        "summary": "Verify getValue/setValue operator translation, prop$delegate pattern, and provideDelegate validation",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_lazy_modes_and_local_delegate():
    compute_calls = 0

    class LazyBox:
        def __init__(self, mode: str, initializer):
            self.mode = mode
            self._init = initializer
            self._computed = False
            self._value = None

        def get(self):
            if not self._computed:
                val = self._init()
                self._value = val
                self._computed = True
            return self._value

    def init_hello():
        nonlocal compute_calls
        compute_calls += 1
        return "Hello"

    lazy_val = LazyBox("SYNCHRONIZED", init_hello)
    first_read = lazy_val.get()
    second_read = lazy_val.get()

    # Exception retry in SYNCHRONIZED lazy
    attempts = 0

    def flaky_init():
        nonlocal attempts
        attempts += 1
        if attempts == 1:
            raise RuntimeError("transient error")
        return "recovered"

    flaky_lazy = LazyBox("SYNCHRONIZED", flaky_init)
    first_failed = False
    try:
        flaky_lazy.get()
    except RuntimeError:
        first_failed = True
    recovered_val = flaky_lazy.get()

    # Local delegated lazy not evaluated if branch skips access
    local_runs = 0

    def process(use_it: bool):
        def _compute():
            nonlocal local_runs
            local_runs += 1
            return "KOTLIN"

        local_lazy = LazyBox("SYNCHRONIZED", _compute)
        return local_lazy.get() if use_it else "skipped"

    skipped_res = process(False)
    runs_after_skip = local_runs
    used_res = process(True)

    actual = {
        "lazy_reads": [first_read, second_read],
        "compute_calls": compute_calls,
        "retry_after_exception": [first_failed, recovered_val, attempts],
        "local_skip": [skipped_res, runs_after_skip, used_res, local_runs],
    }
    expected = {
        "lazy_reads": ["Hello", "Hello"],
        "compute_calls": 1,
        "retry_after_exception": [True, "recovered", 2],
        "local_skip": ["skipped", 0, "KOTLIN", 1],
    }
    return {
        "name": "lazy_modes_and_local_delegate",
        "summary": "Verify lazy caching, exception retry on SYNCHRONIZED mode, and unused local lazy deferral",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_observable_vetoable_map_and_notnull():
    # Delegates.observable
    obs_log = []
    obs_val = "初始值"

    def set_obs(new_val: str):
        nonlocal obs_val
        old = obs_val
        obs_val = new_val
        obs_log.append(f"name:{old} -> {new_val}")

    set_obs("第一次赋值")
    set_obs("第二次赋值")

    # Delegates.vetoable
    age = 0

    def set_age(new_val: int):
        nonlocal age
        if 0 <= new_val <= 150:
            age = new_val

    set_age(25)
    after_25 = age
    set_age(-1)
    after_neg = age
    set_age(200)
    after_200 = age

    # Map / MutableMap delegation
    backing_map = {"name": "蓝色天空", "url": "mbsky.cn"}
    initial_map_name = backing_map["name"]
    backing_map["name"] = "KOTLIN"

    # Delegates.notNull
    sentinel = object()
    not_null_store = sentinel
    uninit_threw = False
    try:
        if not_null_store is sentinel:
            raise RuntimeError("IllegalStateException: Property notNullBar should be initialized before get.")
    except RuntimeError:
        uninit_threw = True
    not_null_store = "bar"

    actual = {
        "observable_log": obs_log,
        "vetoable_ages": [after_25, after_neg, after_200],
        "map_initial_and_written": [initial_map_name, backing_map["name"]],
        "not_null_uninit_threw": uninit_threw,
        "not_null_after_set": not_null_store,
    }
    expected = {
        "observable_log": ["name:初始值 -> 第一次赋值", "name:第一次赋值 -> 第二次赋值"],
        "vetoable_ages": [25, 25, 25],
        "map_initial_and_written": ["蓝色天空", "KOTLIN"],
        "not_null_uninit_threw": True,
        "not_null_after_set": "bar",
    }
    return {
        "name": "observable_vetoable_map_and_notnull",
        "summary": "Verify Delegates.observable, Delegates.vetoable, MutableMap write-back, and Delegates.notNull",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_class_delegation_and_override(),
        case_custom_property_delegate_and_provide_delegate(),
        case_lazy_modes_and_local_delegate(),
        case_observable_vetoable_map_and_notnull(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。

入口文件:projects/kotlin-delegated-lab/explore-delegated.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-delegated.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Kotlin

课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip

下载课程关联工程包:Kotlin

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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