"""Offline Scala semantic verification lab for Chapter 19 (classes-objects)."""
import json
VERSION = "CPython 3.12.14 offline Scala 2.13/3 semantic verifier (scalac absent)"
def case_point_class_instantiation_and_move():
class Point:
def __init__(self, xc, yc):
self.x = xc
self.y = yc
def move(self, dx, dy):
self.x += dx
self.y += dy
pt = Point(10, 20)
pt.move(10, 10)
expected = {"x": 20, "y": 30}
actual = {"x": pt.x, "y": pt.y}
return {
"name": "point_class_instantiation_and_move",
"summary": "验证 Point 类主构造参数初始化字段与 move(dx, dy) 状态更新",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_location_inheritance_and_override():
class Point:
def __init__(self, xc, yc):
self.xc = xc
self.yc = yc
self.x = xc
self.y = yc
def move(self, dx, dy):
self.x += dx
self.y += dy
class Location(Point):
def __init__(self, xc, yc, zc):
super().__init__(xc, yc)
self.zc = zc
self.z = zc
def move3d(self, dx, dy, dz):
self.x += dx
self.y += dy
self.z += dz
loc = Location(10, 20, 15)
loc.move3d(10, 10, 5)
expected = {"x": 20, "y": 30, "z": 20, "single_class_inheritance": True}
actual = {"x": loc.x, "y": loc.y, "z": loc.z, "single_class_inheritance": issubclass(Location, Point)}
return {
"name": "location_inheritance_and_override",
"summary": "验证子类 Location 通过主构造器向父类 Point 传参并扩展三维坐标方法",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_person_employee_super_tostring():
class Person:
def __init__(self):
self.name = ""
def __str__(self):
return f"{self.__class__.__name__}[name={self.name}]"
class Employee(Person):
def __init__(self):
super().__init__()
self.salary = 0.0
def __str__(self):
return f"{super().__str__()}[salary={self.salary}]"
fred = Employee()
fred.name = "Fred"
fred.salary = 50000.0
expected = {"to_string": "Employee[name=Fred][salary=50000.0]"}
actual = {"to_string": str(fred)}
return {
"name": "person_employee_super_tostring",
"summary": "验证重写非抽象方法 toString 时结合 super.toString 复用父类输出",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_singleton_and_companion_marker_factory():
creation_log = []
class Marker:
_token = object()
def __init__(self, color, token):
if token is not Marker._token:
raise PermissionError("private_constructor")
self.color = color
creation_log.append(f"创建{self}")
def __str__(self):
return f"颜色标记:{self.color}"
class MarkerCompanion:
_markers = {
"red": Marker("red", Marker._token),
"blue": Marker("blue", Marker._token),
"green": Marker("green", Marker._token),
}
@classmethod
def apply(cls, color):
return cls._markers.get(color)
@classmethod
def get_marker(cls, color):
return cls._markers.get(color)
direct_err = ""
try:
Marker("yellow", None)
except PermissionError as exc:
direct_err = str(exc)
expected = {
"creation_log": ["创建颜色标记:red", "创建颜色标记:blue", "创建颜色标记:green"],
"apply_red": "颜色标记:red",
"get_blue": "颜色标记:blue",
"unknown_is_none": True,
"direct_new_blocked": "private_constructor",
}
actual = {
"creation_log": creation_log,
"apply_red": str(MarkerCompanion.apply("red")),
"get_blue": str(MarkerCompanion.get_marker("blue")),
"unknown_is_none": MarkerCompanion.apply("yellow") is None,
"direct_new_blocked": direct_err,
}
return {
"name": "singleton_and_companion_marker_factory",
"summary": "验证私有主构造器配伴生对象工厂 apply/getMarker 的单例池管理模式",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_point_class_instantiation_and_move(),
case_location_inheritance_and_override(),
case_person_employee_super_tostring(),
case_singleton_and_companion_marker_factory(),
]
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-classes-objects-lab/explore-classes-objects.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-classes-objects.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a2409.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2411.zip