"""Offline Rust semantic verifier for Chapter 25: Object-Oriented Patterns (encapsulation, trait-object dyn dispatch, composition)."""
from abc import ABC, abstractmethod
from dataclasses import dataclass
import json
class AccessDeniedError(Exception):
pass
class ClassName:
"""Models second.rs::ClassName with private field + private_method encapsulated behind pub API."""
def __init__(self, value: int) -> None:
self._field = value # private to module `second`
@classmethod
def new(cls, value: int) -> "ClassName":
return cls(value)
def public_method(self) -> list[str]:
log = ["from public method"]
log.append(self._private_method())
return log
def _private_method(self) -> str:
return "from private method"
def external_get_field(self, same_module: bool) -> int:
if not same_module:
raise AccessDeniedError("field `field` of struct `ClassName` is private")
return self._field
class Drawable(ABC):
"""Models a Rust object-safe trait used via Box<dyn Drawable>."""
@abstractmethod
def draw(self) -> str: ...
@dataclass
class Button(Drawable):
width: int
height: int
label: str
def draw(self) -> str:
return f"Button({self.width}x{self.height}, {self.label})"
@dataclass
class SelectBox(Drawable):
options: list[str]
def draw(self) -> str:
return f"SelectBox({','.join(self.options)})"
@dataclass
class BaseWidget:
id: str
def tag(self) -> str:
return f"widget:{self.id}"
@dataclass
class ComposedPanel:
"""Models Rust composition (has-a) in place of classical class field inheritance."""
base: BaseWidget
title: str
def render_header(self) -> str:
return f"{self.base.tag()}|{self.title}"
def run_cases() -> list[dict]:
cases = []
# Case 1: Module + struct encapsulation (pub new/public_method calling private_method)
obj = ClassName.new(1024)
output_lines = obj.public_method()
external_blocked = False
try:
obj.external_get_field(same_module=False)
except AccessDeniedError:
external_blocked = True
actual_1 = {
"public_call_output": output_lines,
"external_private_field_blocked": external_blocked,
"internal_field_value": obj.external_get_field(same_module=True),
}
expected_1 = {
"public_call_output": ["from public method", "from private method"],
"external_private_field_blocked": True,
"internal_field_value": 1024,
}
cases.append(dict(
name="module_struct_encapsulation",
summary="Verify pub constructor/method invokes private_method while external module cannot access private field",
expected=expected_1,
actual=actual_1,
passed=actual_1 == expected_1,
))
# Case 2: Polymorphism via heterogeneous Vec<Box<dyn Drawable>> trait objects
screen_components: list[Drawable] = [
Button(width=80, height=30, label="OK"),
SelectBox(options=["Rust", "Cargo"]),
]
rendered = [comp.draw() for comp in screen_components]
actual_2 = {
"component_count": len(rendered),
"dyn_dispatch_output": rendered,
}
expected_2 = {
"component_count": 2,
"dyn_dispatch_output": ["Button(80x30, OK)", "SelectBox(Rust,Cargo)"],
}
cases.append(dict(
name="trait_object_dynamic_dispatch",
summary="Verify heterogeneous Vec<Box<dyn Drawable>> dynamic dispatch across Button and SelectBox",
expected=expected_2,
actual=actual_2,
passed=actual_2 == expected_2,
))
# Case 3: Composition over classical inheritance
panel = ComposedPanel(base=BaseWidget("nav-1"), title="Settings")
actual_3 = {
"composed_header": panel.render_header(),
"delegated_base_tag": panel.base.tag(),
}
expected_3 = {
"composed_header": "widget:nav-1|Settings",
"delegated_base_tag": "widget:nav-1",
}
cases.append(dict(
name="composition_over_inheritance",
summary="Verify Rust embeds parent struct as field to reuse state/behavior without class inheritance",
expected=expected_3,
actual=actual_3,
passed=actual_3 == expected_3,
))
return cases
def main() -> None:
payload = {
"version": "CPython 3.12.14 offline Rust semantic verifier (rustc absent)",
"cases": run_cases(),
}
print(json.dumps(payload, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/rust-object-lab/explore-object.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-object.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a1193.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1212.zip