蓝色天空网 · mbsky.com 全部实例

原型:浅复制、深复制与对象图身份

复制策略要说明哪些引用独立,哪些引用有意共享。

本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。

Python 3.12.14 · 19 项实际检查 · 当前入口SHA256 6210d25aee001dc0f6d13f88848bfc2ec21c788bda8d892541356d3dd39ad1a8

检查项实际结果预期结果
shallow object newfalsefalse
shallow nested list sharedtruetrue
deep nested list distinctfalsefalse
deep preserves internal aliasestruetrue
deep cycle points to new roottruetrue
original nested untouched["base"]["base"]
immutable identity need not be newtruetrue
registry prototype unchanged"蓝色天空网""蓝色天空网"
missing prototype explicit"KeyError""KeyError"
unregister[][]
custom shared dependencytruetrue
custom owned statefalsefalse
custom memo cycletruetrue
game cloned skills isolated["block"]["block"]
game equipment original intact11
document template sections not shared11
versioned prototype registry[1, 2][1, 2]
removed version missing"KeyError""KeyError"
explicit template date not fake runtime date"2026-11-03""2026-11-03"

本章源码与生成文件

下载独立入口 共享实现 补充实例实现 本章结果JSON

查看当前核心代码
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))

上图是本站运行生成文件,不能当作来源原图已采集。