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

访问者:双重分派、返回值与新增元素的代价

对象结构稳定时,把相关操作集中在独立访问者中。

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

Python 3.12.14 · 18 项实际检查 · 当前入口SHA256 7f0147f094419030f76491d9065d48084c3a91690af42eab087870f127472100

检查项实际结果预期结果
accept returns circle resulttruetrue
rectangle and triangle areas[24, 6.0][24, 6.0]
rectangle triangle perimeters[20, 12][20, 12]
circle precise perimetertruetrue
negative radius"ValueError""ValueError"
degenerate triangle"ValueError""ValueError"
nan dimension"ValueError""ValueError"
actual SVG elements["circle", "rect", "polygon"]["circle", "rect", "polygon"]
escape source textfalsefalse
escaped ampersandtruetrue
whitespace token counts not Chinese word count[1, 4, 3][1, 4, 3]
total is sum88
visitor accumulates on reuse99
fresh visitor starts000
heading level validation"ValueError""ValueError"
new element requires visitor support"AttributeError""AttributeError"
empty mean explicitly unavailablenullnull
aggregate count and actual mean[2, 12.0, 6.0][2, 12.0, 6.0]

本章源码与生成文件

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

查看当前核心代码
from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *

def visitor(c,out):
    import math
    shapes=[VisitCircle(5),VisitRect(4,6),VisitTriangle(3,4,5)];areas=[s.accept(AreaVisitor())for s in shapes];perimeters=[s.accept(PerimeterVisitor())for s in shapes]
    c.eq("accept returns circle result",math.isclose(areas[0],math.pi*25),True);c.eq("rectangle and triangle areas",areas[1:],[24,6.0]);c.eq("rectangle triangle perimeters",perimeters[1:],[20,12]);c.eq("circle precise perimeter",math.isclose(perimeters[0],10*math.pi),True)
    c.raises("negative radius",ValueError,lambda:VisitCircle(-1));c.raises("degenerate triangle",ValueError,lambda:VisitTriangle(1,2,3));c.raises("nan dimension",ValueError,lambda:VisitRect(float("nan"),1))
    svg='<svg xmlns="http://www.w3.org/2000/svg" width="120" height="50">'+''.join(s.accept(SvgVisitor())for s in shapes)+'</svg>';path=out/"visited-shapes.svg";path.write_text(svg,encoding="utf8");c.eq("actual SVG elements",[n.tag.rsplit('}',1)[-1]for n in ET.parse(path).getroot()],["circle","rect","polygon"])
    document=[DocElement("heading","蓝色天空网",1),DocElement("paragraph",'<script>literal</script> & learn Python'),DocElement("list",["one item","中文段落"])]
    html_body="".join(e.accept(HtmlDocVisitor())for e in document);(out/"visitor-document.html").write_text('<!doctype html><meta charset="utf-8"><title>蓝色天空网 · mbsky.com</title>'+html_body,encoding="utf8")
    c.eq("escape source text",'<script>'in html_body,False);c.eq("escaped ampersand",'&amp;'in html_body,True)
    counter=TokenCountVisitor();counts=[e.accept(counter)for e in document];c.eq("whitespace token counts not Chinese word count",counts,[1,4,3]);c.eq("total is sum",counter.total,sum(counts))
    document[0].accept(counter);c.eq("visitor accumulates on reuse",counter.total,sum(counts)+1);c.eq("fresh visitor starts0",TokenCountVisitor().total,0)
    c.raises("heading level validation",ValueError,lambda:DocElement("heading","x",7).accept(HtmlDocVisitor()))
    class MissingTriangleVisitor:
        def visit_circle(self,shape):return 0
    c.raises("new element requires visitor support",AttributeError,lambda:shapes[2].accept(MissingTriangleVisitor()))

def extra_visitor(c,out):
    class Statistics(AreaVisitor):
        def __init__(self):self.total=0;self.count=0
        def record(self,value):self.total+=value;self.count+=1;return value
        def visit_circle(self,s):return self.record(super().visit_circle(s))
        def visit_rectangle(self,s):return self.record(super().visit_rectangle(s))
        def visit_triangle(self,s):return self.record(super().visit_triangle(s))
        def average(self):return self.total/self.count if self.count else None
    stats=Statistics();c.eq("empty mean explicitly unavailable",stats.average(),None)
    for shape in (VisitRect(2,3),VisitTriangle(3,4,5)):shape.accept(stats)
    c.eq("aggregate count and actual mean",(stats.count,stats.total,stats.average()),(2,12.0,6.0))

def run_case(out):
    c=Checks()
    visitor(c,out)
    extra_visitor(c,out)
    return {"chapter":'python-visitor',"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))
本章实际Python运行生成的SVG:visited-shapes.svg

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