蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 Dart 命名构造函数、初始化列表断言、Getter/Setter 校验与 static 状态

PYTHONWindows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。explore-classes-and-objects.py
explore-classes-and-objects.py239 行
"""Offline Dart 3.x semantic verification lab for Chapter 10 (classes-and-objects)."""
import json

VERSION = "CPython 3.12.14 offline Dart 3.x semantic verifier (dart SDK absent)"


def case_class_instantiation_and_constructors():
    class User:
        def __init__(self):
            self.name = ""
            self.age = 0

        def is_adult(self) -> bool:
            return self.age >= 18

    class Student:
        def __init__(self, name: str, age: int):
            self.name = name
            self.age = age

    class Point:
        def __init__(self, x: float, y: float):
            self.x = float(x)
            self.y = float(y)

        @classmethod
        def origin(cls):
            return cls(0.0, 0.0)

        @classmethod
        def diagonal(cls, value: float):
            return cls(value, value)

        def __str__(self) -> str:
            return f"Point({self.x}, {self.y})"

    u1 = User()
    u1.name, u1.age = "bluesky", 10
    u2 = User()
    u2.name, u2.age = "小明", 20

    s1 = Student("bluesky", 10)
    points = [str(Point(3, 4)), str(Point.origin()), str(Point.diagonal(5))]

    expected = {
        "u1_adult": False,
        "u2_adult": True,
        "instances_isolated": True,
        "student_info": "bluesky:10",
        "points": ["Point(3.0, 4.0)", "Point(0.0, 0.0)", "Point(5.0, 5.0)"],
    }
    actual = {
        "u1_adult": u1.is_adult(),
        "u2_adult": u2.is_adult(),
        "instances_isolated": u1.name != u2.name,
        "student_info": f"{s1.name}:{s1.age}",
        "points": points,
    }
    return {
        "name": "class_instantiation_and_constructors",
        "summary": "校验对象独立状态、语法糖构造函数及 Point.origin / Point.diagonal 命名构造函数",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_initializer_list_and_assert():
    class Person:
        def __init__(self, name: str, birth_year: int, *, debug_mode: bool = True):
            if debug_mode and not (birth_year > 1900):
                raise AssertionError("出生年份不合理")
            self.name = name
            self.birth_year = birth_year
            self.age = 2026 - birth_year

    p_ok = Person("bluesky", 2016, debug_mode=True)
    debug_caught = False
    try:
        Person("error", 1800, debug_mode=True)
    except AssertionError:
        debug_caught = True
    p_release = Person("legacy", 1800, debug_mode=False)

    expected = {
        "computed_age": 10,
        "debug_assert_triggered": True,
        "release_ignores_assert_age": 226,
    }
    actual = {
        "computed_age": p_ok.age,
        "debug_assert_triggered": debug_caught,
        "release_ignores_assert_age": p_release.age,
    }
    return {
        "name": "initializer_list_and_assert",
        "summary": "校验构造函数初始化列表计算 final 字段及 assert 仅在 debug 模式生效的特性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_encapsulation_getters_and_setters():
    class BankAccount:
        def __init__(self, owner: str, account_number: str):
            self.owner = owner
            self._account_number = account_number
            self._balance = 0.0

        def deposit(self, amount: float):
            if amount > 0:
                self._balance += amount

        def withdraw(self, amount: float) -> bool:
            if 0 < amount <= self._balance:
                self._balance -= amount
                return True
            return False

        @property
        def balance_snapshot(self) -> float:
            return self._balance

    class Circle:
        def __init__(self, radius: float):
            self._radius = float(radius)

        @property
        def diameter(self) -> float:
            return self._radius * 2

        @property
        def area(self) -> float:
            return 3.14159 * self._radius * self._radius

        @property
        def radius(self) -> float:
            return self._radius

        @radius.setter
        def radius(self, value: float):
            if value <= 0:
                raise ValueError("ArgumentError: 半径必须大于 0")
            self._radius = float(value)

    acc = BankAccount("BlueSky", "6222-0000-1234")
    acc.deposit(1000)
    w1 = acc.withdraw(300)
    w2 = acc.withdraw(800)

    c = Circle(5)
    area_5 = f"{c.area:.2f}"
    c.radius = 10
    diam_10 = c.diameter
    invalid_rejected = False
    try:
        c.radius = -1
    except ValueError:
        invalid_rejected = True

    expected = {
        "withdraw_300": True,
        "withdraw_800": False,
        "final_balance": 700.0,
        "circle_area_5": "78.54",
        "circle_diameter_10": 20.0,
        "negative_radius_rejected": True,
    }
    actual = {
        "withdraw_300": w1,
        "withdraw_800": w2,
        "final_balance": acc.balance_snapshot,
        "circle_area_5": area_5,
        "circle_diameter_10": diam_10,
        "negative_radius_rejected": invalid_rejected,
    }
    return {
        "name": "encapsulation_getters_and_setters",
        "summary": "验证 BankAccount 余额封装保护及 Circle 的计算属性 Getter 与带校验 Setter",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_static_members_shared_state():
    class Counter:
        total_count = 0

        def __init__(self, label: str):
            self.label = label
            Counter.total_count += 1

        @staticmethod
        def is_valid_label(label: str) -> bool:
            return len(label) > 0 and len(label) <= 20

    valid_before_inst = Counter.is_valid_label("test")
    invalid_empty = Counter.is_valid_label("")
    _c1 = Counter("A")
    after_1 = Counter.total_count
    _c2, _c3 = Counter("B"), Counter("C")
    after_3 = Counter.total_count

    expected = {
        "valid_label_without_instance": True,
        "empty_label_valid": False,
        "count_after_1": 1,
        "count_after_3": 3,
    }
    actual = {
        "valid_label_without_instance": valid_before_inst,
        "empty_label_valid": invalid_empty,
        "count_after_1": after_1,
        "count_after_3": after_3,
    }
    return {
        "name": "static_members_shared_state",
        "summary": "校验 static 类级共享状态与无需实例化的静态工具方法行为",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_class_instantiation_and_constructors(),
        case_initializer_list_and_assert(),
        case_encapsulation_getters_and_setters(),
        case_static_members_shared_state(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。

入口文件:projects/dart-classes-and-objects-lab/explore-classes-and-objects.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-classes-and-objects.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Dart 3.x 语义验证器(本机未安装原生 Dart SDK)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Dart

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2536.zip

下载课程关联工程包:Dart

课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a2534.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习