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

离线校验原型表对象、冒号 self 语法糖、Square/Dog 继承重写、多态与闭包封装

PYTHONWindows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。explore-object-oriented.py
explore-object-oriented.py204 行
"""Offline Lua 5.4 semantic verification lab for Chapter 22 (object-oriented)."""
import json

VERSION = "CPython 3.12.14 offline Lua 5.4 semantic verifier (lua interpreter absent)"


class ProtoObject:
    """Faithful Lua table + metatable(__index) prototype object model."""

    def __init__(self, fields=None, proto=None):
        self.fields = dict(fields or {})
        self.proto = proto

    def get(self, key):
        if key in self.fields:
            return self.fields[key]
        if self.proto is not None:
            return self.proto.get(key)
        return None

    def set(self, key, val):
        self.fields[key] = val

    def call_colon(self, method_name, *args):
        """Syntactic sugar `obj:method(...)` == `obj.method(obj, ...)`."""
        fn = self.get(method_name)
        return fn(self, *args)


def case_prototype_class_and_colon_sugar():
    Person = ProtoObject({"name": "", "age": 0})

    def person_new(cls, name, age):
        obj = ProtoObject({"name": name, "age": age}, proto=cls)
        return obj

    def person_introduce(self):
        return f"My name is {self.get('name')} and I am {self.get('age')} years old."

    Person.set("new", person_new)
    Person.set("introduce", person_introduce)

    p1 = Person.call_colon("new", "Alice", 30)
    via_colon = p1.call_colon("introduce")
    # Explicit dot call passing self manually yields the exact same result
    via_dot = p1.get("introduce")(p1)
    expected = {
        "via_colon": "My name is Alice and I am 30 years old.",
        "colon_equals_dot_with_self": True,
        "dot_field_access": ["Alice", 30],
    }
    actual = {
        "via_colon": via_colon,
        "colon_equals_dot_with_self": via_colon == via_dot,
        "dot_field_access": [p1.get("name"), p1.get("age")],
    }
    return {
        "name": "prototype_class_and_colon_sugar",
        "summary": "校验表+元表 __index 模拟 Person 类及冒号语法糖 obj:method() 与 obj.method(obj) 等价性",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_rectangle_and_square_inheritance():
    Rectangle = ProtoObject({"area": 0, "length": 0, "breadth": 0})

    def rect_new(cls, o=None, length=0, breadth=0):
        obj = o if o is not None else ProtoObject()
        obj.proto = cls
        obj.set("length", length or 0)
        obj.set("breadth", breadth or 0)
        obj.set("area", obj.get("length") * obj.get("breadth"))
        return obj

    def rect_print_area(self):
        return f"矩形面积为 {self.get('area')}"

    Rectangle.set("new", rect_new)
    Rectangle.set("printArea", rect_print_area)

    Square = Rectangle.call_colon("new")

    def square_new(cls, o=None, side=0):
        obj = o if o is not None else ProtoObject()
        obj.proto = cls
        s = side or 0
        obj.set("length", s)
        obj.set("breadth", s)
        obj.set("area", s * s)
        return obj

    Square.set("new", square_new)

    r1 = Rectangle.call_colon("new", None, 5, 10)
    r2 = Rectangle.call_colon("new", None, 7, 3)
    sq = Square.call_colon("new", None, 4)

    expected = {
        "rect1_area": "矩形面积为 50",
        "rect2_area": "矩形面积为 21",
        "square_inherits_printArea": "矩形面积为 16",
    }
    actual = {
        "rect1_area": r1.call_colon("printArea"),
        "rect2_area": r2.call_colon("printArea"),
        "square_inherits_printArea": sq.call_colon("printArea"),
    }
    return {
        "name": "rectangle_and_square_inheritance",
        "summary": "校验 Square 原型继承 Rectangle,重写构造函数同时沿原型链复用 printArea 方法",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_method_override_and_polymorphism():
    Animal = ProtoObject({"name": "Unknown"})
    Animal.set("new", lambda cls, o=None, name="Unknown": ProtoObject({"name": name or "Unknown"}, proto=cls))
    Animal.set("speak", lambda self: f"{self.get('name')} makes a sound.")

    Dog = Animal.call_colon("new")
    Dog.set("new", lambda cls, o=None, name="Unknown", breed="Unknown": ProtoObject({"name": name, "breed": breed}, proto=cls))
    Dog.set("speak", lambda self: f"{self.get('name')} barks.")

    a = Animal.call_colon("new", None, "Generic Animal")
    d = Dog.call_colon("new", None, "Buddy", "Golden Retriever")

    Person = ProtoObject()
    Person.set("new", lambda cls, name="", age=0: ProtoObject({"name": name, "age": age}, proto=cls))
    Person.set("greet", lambda self: f"Hello, my name is {self.get('name')}")

    Student = Person.call_colon("new")
    Student.set("greet", lambda self: f"Hi, I'm a student and my name is {self.get('name')}")

    p2 = Person.call_colon("new", "Charlie", 25)
    s2 = Student.call_colon("new", "David", 18)

    expected = {
        "animal_speak": "Generic Animal makes a sound.",
        "dog_override_speak": "Buddy barks.",
        "poly_person": "Hello, my name is Charlie",
        "poly_student": "Hi, I'm a student and my name is David",
    }
    actual = {
        "animal_speak": a.call_colon("speak"),
        "dog_override_speak": d.call_colon("speak"),
        "poly_person": p2.call_colon("greet"),
        "poly_student": s2.call_colon("greet"),
    }
    return {
        "name": "method_override_and_polymorphism",
        "summary": "校验子类重写父类方法(Animal/Dog)与同名接口多态动态派发(Person/Student)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_encapsulation_and_abstraction():
    def new_encapsulated_person(name, age):
        state = {"name": name, "age": age}  # closure-private state
        return {
            "getName": lambda: state["name"],
            "setName": lambda v: state.__setitem__("name", v),
            "showInfo": lambda: [f"Name: {state['name']}", f"Age: {state['age']}"],
        }

    obj = new_encapsulated_person("Alice", 28)
    obj["setName"]("Alicia")
    expected = {
        "private_field_hidden": True,
        "name_via_getter": "Alicia",
        "abstract_info": ["Name: Alicia", "Age: 28"],
    }
    actual = {
        "private_field_hidden": "name" not in obj,
        "name_via_getter": obj["getName"](),
        "abstract_info": obj["showInfo"](),
    }
    return {
        "name": "encapsulation_and_abstraction",
        "summary": "校验通过 getter/setter 与闭包状态隐藏内部字段(封装)并暴露 showInfo 统一接口(抽象)",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_prototype_class_and_colon_sugar(),
        case_rectangle_and_square_inheritance(),
        case_method_override_and_polymorphism(),
        case_encapsulation_and_abstraction(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


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

运行环境:Windows x64、CPython 3.12.14 离线 Lua 5.4 语义验证器(本机未安装原生 lua/luac 解释器)。

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

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

下载课程关联工程包:Lua

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

下载课程关联工程包:Lua

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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