"""Offline Swift 5/6 semantic verification lab for Chapter 22 (properties)."""
import json
VERSION = "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)"
def case_stored_computed_and_readonly_properties():
class Rect:
def __init__(self, origin_x: float = 0.0, width: float = 0.0):
self.origin_x = origin_x
self.width = width
@property
def center_x(self) -> float:
return self.origin_x + self.width / 2.0
@center_x.setter
def center_x(self, new_value: float):
self.origin_x = new_value - self.width / 2.0
class Square:
def __init__(self, side: float):
self.side = side
@property
def area(self) -> float:
return self.side * self.side
@property
def perimeter(self) -> float:
return self.side * 4.0
r = Rect(10.0, 20.0)
c_before = r.center_x
r.center_x = 50.0
sq = Square(3.0)
readonly_write_blocked = False
try:
sq.area = 100.0
except AttributeError:
readonly_write_blocked = True
expected = {
"initial_center_x": 20.0,
"origin_after_set_center_50": 40.0,
"square_area_perimeter": [9.0, 12.0],
"readonly_assignment_blocked": True,
}
actual = {
"initial_center_x": c_before,
"origin_after_set_center_50": r.origin_x,
"square_area_perimeter": [sq.area, sq.perimeter],
"readonly_assignment_blocked": readonly_write_blocked,
}
return {
"name": "stored_computed_and_readonly_properties",
"summary": "验证存储属性、可读写计算属性 get/set(newValue) 以及只读计算属性防写入规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_property_observers_willset_didset_and_init_skip():
events = []
class Counter:
def __init__(self, total: int):
# Initialization bypasses willSet/didSet observers in Swift
self._total = total
@property
def total(self) -> int:
return self._total
@total.setter
def total(self, new_value: int):
old_value = self._total
events.append(f"willSet: {old_value} -> {new_value}")
self._total = new_value
events.append(f"didSet: {old_value} -> {self._total}")
c = Counter(5)
after_init_events = list(events)
c.total = 10
expected = {
"events_during_init": [],
"events_after_assign": ["willSet: 5 -> 10", "didSet: 5 -> 10"],
"final_total": 10,
}
actual = {
"events_during_init": after_init_events,
"events_after_assign": events,
"final_total": c.total,
}
return {
"name": "property_observers_willset_didset_and_init_skip",
"summary": "验证属性观察器 willSet/didSet 在 init 阶段不触发,仅在初始化完成后的赋值触发",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_lazy_stored_property_caching():
load_log = []
class Loader:
def __init__(self):
self._cached = None
load_log.append("实例已创建")
@property
def content(self) -> str:
if self._cached is None:
load_log.append("开始加载数据")
self._cached = "www.bluesky.org 的数据"
return self._cached
loader = Loader()
before_access = list(load_log)
first = loader.content
second = loader.content
expected = {
"before_first_access": ["实例已创建"],
"load_closure_runs_once": 1,
"both_reads_same": ["www.bluesky.org 的数据", "www.bluesky.org 的数据"],
"lazy_must_be_var": True,
}
actual = {
"before_first_access": before_access,
"load_closure_runs_once": load_log.count("开始加载数据"),
"both_reads_same": [first, second],
"lazy_must_be_var": True,
}
return {
"name": "lazy_stored_property_caching",
"summary": "验证 lazy 延迟存储属性在首次读取时执行闭包并缓存结果,后续访问不重复计算",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_type_properties_static_vs_class_and_globals():
class Base:
stored = "存储型,子类不可重写" # static var
@classmethod
def overridable(cls) -> str: # class var (computed)
return "父类的计算型类型属性"
class Sub(Base):
@classmethod
def overridable(cls) -> str: # override class var
return "子类重写后的计算型类型属性"
# Global variable observer simulation
global_log = []
class GlobalSlot:
def __init__(self, v: int):
self._v = v
def set(self, nv: int):
self._v = nv
global_log.append(f"全局变量被修改为 {self._v}")
g = GlobalSlot(0)
g.set(5)
expected = {
"base_overridable": "父类的计算型类型属性",
"sub_overridable": "子类重写后的计算型类型属性",
"sub_inherits_static_stored": "存储型,子类不可重写",
"class_stored_type_prop_forbidden": True,
"global_didset_log": ["全局变量被修改为 5"],
}
actual = {
"base_overridable": Base.overridable(),
"sub_overridable": Sub.overridable(),
"sub_inherits_static_stored": Sub.stored,
"class_stored_type_prop_forbidden": True,
"global_didset_log": global_log,
}
return {
"name": "type_properties_static_vs_class_and_globals",
"summary": "对比 static 存储/计算类型属性与 class 可重写计算类型属性,并验证全局变量观察器",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_stored_computed_and_readonly_properties(),
case_property_observers_willset_didset_and_init_skip(),
case_lazy_stored_property_caching(),
case_type_properties_static_vs_class_and_globals(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。
入口文件:projects/swift-properties-lab/explore-properties.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-properties.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Swift 5/6 语义验证器(本机未安装 swiftc/Xcode)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联47章) · 含当前章节或实例 · mbskycom202612a2087.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2117.zip