"""Offline Scala semantic verification lab for Chapter 20 (traits)."""
import json
VERSION = "CPython 3.12.14 offline Scala 2.13/3 semantic verifier (scalac absent)"
def case_equal_trait_abstract_and_concrete_methods():
class EqualTrait:
def is_equal(self, x):
raise NotImplementedError
def is_not_equal(self, x):
return not self.is_equal(x)
class Box(EqualTrait):
def __init__(self, v):
self.v = v
def is_equal(self, x):
return isinstance(x, Box) and x.v == self.v
b1, b2, b3 = Box(5), Box(5), Box(7)
expected = {"b1_eq_b2": True, "b1_neq_b2": False, "b1_neq_b3": True}
actual = {
"b1_eq_b2": b1.is_equal(b2),
"b1_neq_b2": b1.is_not_equal(b2),
"b1_neq_b3": b1.is_not_equal(b3),
}
return {
"name": "equal_trait_abstract_and_concrete_methods",
"summary": "验证 Trait 同时包含抽象方法(isEqual)与默认实现方法(isNotEqual)的契约行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_point_mixin_and_type_check():
class Equal:
def is_equal(self, x):
raise NotImplementedError
def is_not_equal(self, x):
return not self.is_equal(x)
class Point(Equal):
def __init__(self, xc, yc):
self.x = xc
self.y = yc
def is_equal(self, obj):
return isinstance(obj, Point) and obj.x == self.x
p1, p2, p3 = Point(2, 3), Point(2, 4), Point(3, 3)
expected = {
"p1_not_eq_p2": False,
"p1_not_eq_p3": True,
"p1_not_eq_int_2": True,
}
actual = {
"p1_not_eq_p2": p1.is_not_equal(p2),
"p1_not_eq_p3": p1.is_not_equal(p3),
"p1_not_eq_int_2": p1.is_not_equal(2),
}
return {
"name": "point_mixin_and_type_check",
"summary": "复现 Point 混入 Equal 特征并按 x 坐标与类型判定 isNotEqual 的完整输出(false/true/true)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_trait_linearization_and_construction_order():
# Scala linearization: Lin(C) = C :: Lin(T2) ++ Lin(T1) ++ Lin(Super) (rightmost wins, deduplicate keeping rightmost)
def scala_linearize(cls_name, parents_map):
result = [cls_name]
# Merge parents right-to-left keeping rightmost occurrence
for parent in reversed(parents_map.get(cls_name, [])):
for item in scala_linearize(parent, parents_map):
if item in result:
result.remove(item)
result.append(item)
return result
# class Sub extends Base with T1 with T2, where T1 extends Logger, T2 extends Logger
graph = {
"Any": [],
"AnyRef": ["Any"],
"Base": ["AnyRef"],
"Logger": ["AnyRef"],
"T1": ["Logger"],
"T2": ["Logger"],
"Sub": ["Base", "T1", "T2"],
}
lin = scala_linearize("Sub", graph)
ctor_order = list(reversed(lin))
expected = {
"linearization": ["Sub", "T2", "T1", "Logger", "Base", "AnyRef", "Any"],
"construction_order": ["Any", "AnyRef", "Base", "Logger", "T1", "T2", "Sub"],
}
actual = {"linearization": lin, "construction_order": ctor_order}
return {
"name": "trait_linearization_and_construction_order",
"summary": "验证 Scala 特征线性化序列及构造器按线性化逆序(超类->左到右特征->子类)执行规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_diamond_shared_parent_single_init():
# Shared parent trait Logger must be constructed only once in diamond mixin
init_events = []
constructed = set()
def construct_once(name):
if name not in constructed:
constructed.add(name)
init_events.append(name)
for step in ["Base", "Logger", "T1", "Logger", "T2", "Sub"]:
construct_once(step)
expected = {
"init_sequence": ["Base", "Logger", "T1", "T2", "Sub"],
"logger_init_count": 1,
}
actual = {
"init_sequence": init_events,
"logger_init_count": init_events.count("Logger"),
}
return {
"name": "diamond_shared_parent_single_init",
"summary": "验证多特征共享同一父特征时父特征构造器仅执行一次、不会重复构造",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_equal_trait_abstract_and_concrete_methods(),
case_point_mixin_and_type_check(),
case_trait_linearization_and_construction_order(),
case_diamond_shared_parent_single_init(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。
入口文件:projects/scala-traits-lab/explore-traits.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-traits.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2430.zip
课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a2409.zip