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

原型:浅复制、深复制与对象图身份:独立运行与结果核对

PYTHONWindows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Pythonpython-prototype.py
python-prototype.py50 行
from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *

def prototype(c,out):
    original=Prototype("蓝色天空网");shared=["base"];original.parts=[shared,shared];original.links["self"]=original
    shallow=copy(original);deep=original.clone()
    c.eq("shallow object new",shallow is original,False)
    c.eq("shallow nested list shared",shallow.parts is original.parts,True)
    c.eq("deep nested list distinct",deep.parts is original.parts,False)
    c.eq("deep preserves internal aliases",deep.parts[0] is deep.parts[1],True)
    c.eq("deep cycle points to new root",deep.links["self"] is deep,True)
    deep.parts[0].append("extra");c.eq("original nested untouched",original.parts[0],["base"])
    immutable=("shared",);c.eq("immutable identity need not be new",deepcopy(immutable) is immutable,True)
    registry={"v1":original};clone=registry["v1"].clone();clone.name="copy";c.eq("registry prototype unchanged",original.name,"蓝色天空网")
    c.raises("missing prototype explicit",KeyError,lambda:registry["absent"])
    del registry["v1"];c.eq("unregister",list(registry),[])
    class Custom:
        def __init__(self): self.owned=[];self.shared=object();self.child=self
        def __deepcopy__(self,memo):
            result=type(self).__new__(type(self));memo[id(self)]=result
            result.owned=deepcopy(self.owned,memo);result.shared=self.shared;result.child=deepcopy(self.child,memo);return result
    src=Custom();dst=deepcopy(src)
    c.eq("custom shared dependency",dst.shared is src.shared,True)
    c.eq("custom owned state",dst.owned is src.owned,False)
    c.eq("custom memo cycle",dst.child is dst,True)

def extra_prototype(c,out):
    @dataclass
    class CharacterTemplate:
        name:str
        skills:list
        equipment:dict
    hero=CharacterTemplate("template",["block"],{"weapon":{"power":1}});a=deepcopy(hero);b=deepcopy(hero);a.skills.append("dash");a.equipment["weapon"]["power"]=5;c.eq("game cloned skills isolated",b.skills,["block"]);c.eq("game equipment original intact",hero.equipment["weapon"]["power"],1)
    document={"headers":{"title":"学习报告","author":"蓝色天空网","date":"2026-11-03"},"sections":[{"title":"简介","text":"mbsky.com"}],"styles":{"font":"sans-serif"}}
    monthly=deepcopy(document);monthly["headers"]["title"]="月度报告";monthly["sections"].append({"title":"进度","text":"学习记录"});c.eq("document template sections not shared",len(document["sections"]),1)
    registry={"report-v1":deepcopy(document)};registry["report-v2"]=deepcopy(monthly);c.eq("versioned prototype registry",[len(deepcopy(registry[k])["sections"])for k in ("report-v1","report-v2")],[1,2]);del registry["report-v1"];c.raises("removed version missing",KeyError,lambda:registry["report-v1"])
    c.eq("explicit template date not fake runtime date",monthly["headers"]["date"],"2026-11-03")

def run_case(out):
    c=Checks()
    prototype(c,out)
    extra_prototype(c,out)
    return {"chapter":'python-prototype',"checks":c.rows,"passed":True,"scope":"named owned all24chapter named cases only; full source coverage pending"}

if __name__ == "__main__":
    output=Path(sys.argv[1]);output.mkdir(parents=True,exist_ok=False)
    print(json.dumps(run_case(output),ensure_ascii=False,default=repr))
本例需在 Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python

入口文件:projects/patterns-lab/python-prototype.py

预期结果与验证条件观察提示
  • 当前固定输入命名检查符合明确实际结果及失败策略
  • 每章输出、源码和预期分别对应;本地模型不冒充生产系统,未验能力继续单列

请结合实际环境逐项观察。

附件与关联工程包下载

下载课程关联工程包:Python 设计模式

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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