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

离线校验 Ruby 类成员、访问控制、继承覆写、运算符重载、freeze 与 allocate

PYTHONWindows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。explore-object-oriented.py
explore-object-oriented.py220 行
"""Offline Ruby 3.x semantic verification lab for Chapter 31 (object-oriented)."""
import json

VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (MRI ruby absent)"


def case_class_attrs_classvars_and_tos():
    class Box:
        count = 0

        def __init__(self, w, h):
            self.width = w
            self.height = h
            Box.count += 1

        def area(self):
            return self.width * self.height

        def to_s(self):
            return f"(w:{self.width},h:{self.height})"

    b1 = Box(10, 20)
    b1.width, b1.height = 30, 50
    b2 = Box(10, 20)
    expected = {
        "b1_after_setters": [30, 50, 1500],
        "b2_to_s": "(w:10,h:20)",
        "class_count": 2,
    }
    actual = {
        "b1_after_setters": [b1.width, b1.height, b1.area()],
        "b2_to_s": b2.to_s(),
        "class_count": Box.count,
    }
    return {
        "name": "class_attrs_classvars_and_tos",
        "summary": "核验 Box 构造器 initialize、getter/setter(attr_accessor)、实例方法、类变量 @@count 与 to_s",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_access_control_and_inheritance():
    class Box:
        def __init__(self, w, h):
            self._w = w
            self._h = h

        def get_area(self):
            return self._w * self._h

        def call_protected(self, caller_is_subclass_or_self: bool):
            if not caller_is_subclass_or_self:
                raise AttributeError("protected method `printArea' called for Box (NoMethodError)")
            return f"Big box area is : {self._w * self._h}"

    class BigBox(Box):
        def get_area(self):
            return f"Big box area is : {self._w * self._h}"

    box = Box(10, 20)
    big = BigBox(10, 20)
    external_blocked = False
    try:
        box.call_protected(caller_is_subclass_or_self=False)
    except AttributeError:
        external_blocked = True

    expected = {
        "public_area": 200,
        "protected_external_blocked": True,
        "protected_internal_ok": "Big box area is : 200",
        "subclass_override": "Big box area is : 200",
        "is_subclass": True,
    }
    actual = {
        "public_area": box.get_area(),
        "protected_external_blocked": external_blocked,
        "protected_internal_ok": box.call_protected(caller_is_subclass_or_self=True),
        "subclass_override": big.get_area(),
        "is_subclass": issubclass(BigBox, Box),
    }
    return {
        "name": "access_control_and_inheritance",
        "summary": "核验 public/private/protected 访问控制边界以及子类 BigBox < Box 继承与方法覆写",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_operator_overloading_and_freeze():
    class FrozenErrorRb(TypeError):
        pass

    class Box:
        def __init__(self, w, h):
            self._frozen = False
            self._w = w
            self._h = h

        @property
        def width(self):
            return self._w

        @width.setter
        def width(self, val):
            if self._frozen:
                raise FrozenErrorRb("can't modify frozen Box")
            self._w = val

        def freeze(self):
            self._frozen = True
            return self

        def frozen(self):
            return self._frozen

        def __add__(self, other):
            return Box(self._w + other._w, self._h + other._h)

        def __neg__(self):
            return Box(-self._w, -self._h)

        def __mul__(self, scalar):
            return Box(self._w * scalar, self._h * scalar)

    b1 = Box(10, 20)
    b2 = Box(3, 5)
    added = b1 + b2
    negated = -b1
    scaled = b1 * 2
    b1.freeze()
    freeze_blocked = False
    try:
        b1.width = 99
    except FrozenErrorRb:
        freeze_blocked = True

    expected = {
        "added": [13, 25],
        "negated": [-10, -20],
        "scaled": [20, 40],
        "frozen": True,
        "freeze_blocked": True,
    }
    actual = {
        "added": [added._w, added._h],
        "negated": [negated._w, negated._h],
        "scaled": [scaled._w, scaled._h],
        "frozen": b1.frozen(),
        "freeze_blocked": freeze_blocked,
    }
    return {
        "name": "operator_overloading_and_freeze",
        "summary": "核验自定义 +、-@、* 运算符重载与 freeze/frozen? 冻结对象阻断修改(Ruby 3 抛出 FrozenError)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_constants_allocate_and_self():
    class Box:
        BOX_COMPANY = "TATA Inc"
        BOXWEIGHT = 10

        def __init__(self, w, h):
            self.width = w
            self.height = h

        def get_area(self):
            return self.width * self.height

    allocated = Box.__new__(Box)
    allocated.width = None
    allocated.height = None
    alloc_error = False
    try:
        allocated.get_area()
    except TypeError:
        alloc_error = True

    expected = {
        "company_const": "TATA Inc",
        "weight_const": 10,
        "allocate_skips_initialize": True,
        "self_class_in_body": "Class",
        "self_name_in_body": "Box",
    }
    actual = {
        "company_const": Box.BOX_COMPANY,
        "weight_const": Box.BOXWEIGHT,
        "allocate_skips_initialize": alloc_error,
        "self_class_in_body": "Class" if isinstance(Box, type) else "other",
        "self_name_in_body": Box.__name__,
    }
    return {
        "name": "constants_allocate_and_self",
        "summary": "核验类常量 :: 访问、allocate 跳过 initialize 导致未初始化实例变量报错及类体中 self 指向类对象本身",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_class_attrs_classvars_and_tos(),
        case_access_control_and_inheritance(),
        case_operator_overloading_and_freeze(),
        case_constants_allocate_and_self(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


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

运行环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。

入口文件:projects/ruby-object-oriented-lab/explore-object-oriented.py

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

下载课程关联工程包:Ruby

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

下载课程关联工程包:Ruby

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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