"""Offline Kotlin 2.x semantic verifier for Chapter 17 (class-object)."""
from abc import ABC, abstractmethod
import json
import sys
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
class Site:
"""Models Kotlin properties, custom getter (computed, no backing field), and validated setter (backing field)."""
def __init__(self) -> None:
self.name: str = "MBSKY"
self._url: str = "www.mbsky.com"
self._visits: int = 0
self.ignored_writes: int = 0
@property
def url(self) -> str:
return self._url
@property
def info(self) -> str:
return f"{self.name} - {self.url}"
@property
def visits(self) -> int:
return self._visits
@visits.setter
def visits(self, value: int) -> None:
if value < 0:
self.ignored_writes += 1
else:
self._visits = value
class InitOrderDemo:
"""Models Kotlin top-to-bottom interleaved execution of property initializers and init blocks."""
def __init__(self, name: str) -> None:
self.trace: list[str] = []
self._first = f"第一个属性:{name}"
self.trace.append(self._first)
self.trace.append(f"init 块:{name}")
self._second = f"第二个属性:{name}"
self.trace.append(self._second)
class DelegatingSite:
"""Models primary constructor + secondary constructor delegating via this(...)."""
def __init__(self, name: str, url: str) -> None:
self.name = name
self.url = url
self.visits = 0
self.trace = [f"primary({name},{url})"]
@classmethod
def with_default_url(cls, name: str) -> "DelegatingSite":
inst = cls(name, "www.mbsky.com")
inst.trace.append(f"secondary({name})")
return inst
class Token:
"""Models `class Token private constructor(val value: String)` with companion factory."""
_TOKEN_KEY = object()
def __init__(self, value: str, *, _key: object = None) -> None:
if _key is not self._TOKEN_KEY:
raise PermissionError("Primary constructor is private")
self._value = value
@classmethod
def create(cls) -> "Token":
return cls("mbsky-token", _key=cls._TOKEN_KEY)
def describe(self) -> str:
return f"Token({self._value})"
class Shape(ABC):
@abstractmethod
def area(self) -> float:
...
def describe(self) -> str:
return f"面积是 {self.area()}"
class Circle(Shape):
def __init__(self, radius: float) -> None:
self.radius = radius
def area(self) -> float:
return 3.14 * self.radius * self.radius
class Square(Shape):
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side * self.side
def describe(self) -> str:
return "正方形" + super().describe()
class Outer:
def __init__(self, name: str = "OUTER") -> None:
self.name = name
self._secret = "mbsky"
class Nested:
"""Static nested class: no reference to Outer instance."""
def hello(self) -> str:
return "我是嵌套类,拿不到外部类的成员"
def make_inner(self) -> "Outer._Inner":
return self._Inner(self)
class _Inner:
def __init__(self, outer: "Outer") -> None:
self._outer = outer
def hello(self) -> str:
return f"我是内部类,name={self._outer.name},secret={self._outer._secret}"
def outer_name(self) -> str:
return self._outer.name
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: Empty class, properties, custom getter/setter, backing field
s = Site()
s.visits = 100
s.visits = -1
count_val = 21
actual_1 = {
"instantiated_without_new": True,
"computed_info": s.info,
"visits_after_neg_reject": s.visits,
"ignored_neg_writes": s.ignored_writes,
"double_count_computed": count_val * 2,
"computed_val_has_backing_field": False,
}
expected_1 = {
"instantiated_without_new": True,
"computed_info": "MBSKY - www.mbsky.com",
"visits_after_neg_reject": 100,
"ignored_neg_writes": 1,
"double_count_computed": 42,
"computed_val_has_backing_field": False,
}
cases.append({
"name": "class_properties_and_backing_field",
"summary": "Verify property getters/setters, negative-value guard on backing field, and backing-field omission for computed val.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: Primary constructor, init order, secondary this(...) delegation, private constructor
demo = InitOrderDemo("MBSKY")
d_sec = DelegatingSite.with_default_url("Mbsky")
direct_blocked = False
try:
Token("abc")
except PermissionError:
direct_blocked = True
tok = Token.create()
actual_2 = {
"init_trace": demo.trace,
"secondary_delegation_trace": d_sec.trace,
"secondary_url": d_sec.url,
"private_ctor_direct_blocked": direct_blocked,
"factory_token": tok.describe(),
}
expected_2 = {
"init_trace": ["第一个属性:MBSKY", "init 块:MBSKY", "第二个属性:MBSKY"],
"secondary_delegation_trace": ["primary(Mbsky,www.mbsky.com)", "secondary(Mbsky)"],
"secondary_url": "www.mbsky.com",
"private_ctor_direct_blocked": True,
"factory_token": "Token(mbsky-token)",
}
cases.append({
"name": "constructors_init_order_and_private_factory",
"summary": "Verify property/init top-to-bottom order, secondary this() delegation, and private constructor factory.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: Abstract class, nested vs inner class (this@Outer), anonymous object expression
abstract_blocked = False
try:
Shape() # type: ignore[abstract]
except TypeError:
abstract_blocked = True
shapes: list[Shape] = [Circle(2.0), Square(3.0)]
nested = Outer.Nested()
inner = Outer().make_inner()
anon_config = type("AnonConfig", (), {"url": "www.mbsky.com", "timeout": 3000})()
actual_3 = {
"abstract_instantiation_blocked": abstract_blocked,
"shape_descriptions": [sh.describe() for sh in shapes],
"nested_hello": nested.hello(),
"inner_hello": inner.hello(),
"inner_this_at_outer": inner.outer_name(),
"anon_object": f"{anon_config.url} -> {anon_config.timeout}ms",
}
expected_3 = {
"abstract_instantiation_blocked": True,
"shape_descriptions": ["面积是 12.56", "正方形面积是 9.0"],
"nested_hello": "我是嵌套类,拿不到外部类的成员",
"inner_hello": "我是内部类,name=OUTER,secret=mbsky",
"inner_this_at_outer": "OUTER",
"anon_object": "www.mbsky.com -> 3000ms",
}
cases.append({
"name": "abstract_nested_inner_and_anonymous",
"summary": "Verify abstract class polymorphism, nested vs inner class with this@Outer, and anonymous object expressions.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: Class modifiers & access modifiers (protected is subclass-only, NOT same-file/package)
def can_access(modifier: str, caller: str) -> bool:
if modifier == "public":
return True
if modifier == "internal":
return caller in {"same_class", "subclass", "same_file", "same_module"}
if modifier == "protected":
return caller in {"same_class", "subclass"}
if modifier == "private":
return caller == "same_class"
raise ValueError(modifier)
actual_4 = {
"protected_in_subclass": can_access("protected", "subclass"),
"protected_in_same_file_outside": can_access("protected", "same_file"),
"private_in_subclass": can_access("private", "subclass"),
"internal_in_same_module": can_access("internal", "same_module"),
"internal_in_other_module": can_access("internal", "other_module"),
}
expected_4 = {
"protected_in_subclass": True,
"protected_in_same_file_outside": False,
"private_in_subclass": False,
"internal_in_same_module": True,
"internal_in_other_module": False,
}
cases.append({
"name": "class_and_access_modifier_matrix",
"summary": "Verify Kotlin member visibility rules, especially protected (subclass-only, not same-file) and internal (module).",
"expected": expected_4,
"actual": actual_4,
"passed": actual_4 == expected_4,
})
return cases
def main() -> None:
payload = {"version": VERSION, "cases": run_cases()}
sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
入口文件:projects/kotlin-class-object-lab/explore-class-object.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-class-object.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2135.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip