WEB开发网
开发学院软件开发Python Python用多元法泛化多态性 阅读

Python用多元法泛化多态性

 2007-03-29 12:18:17 来源:WEB开发网   
核心提示: 特别是,每个现有的形状类必须在子代类中添加功能,Python用多元法泛化多态性(6),这使维护工作陷入了组合的复杂性和困难当中,相比之下

特别是,每个现有的形状类必须在子代类中添加功能,这使维护工作陷入了组合的复杂性和困难当中。

相比之下,多分派技术就简单多了:

清单 6. 用于性能扩展的多元法

# Base rules (stipulate combination is order independent)
class Circle(Shape): pass
class Square(Shape): pass
def circle_with_square(circle, square): ...
def circle_with_circle(circle, circle): ...
def square_with_square(square, square): ...
combine = Dispatch()
combine.add_rule((Circle, Square), circle_with_square)
combine.add_rule((Circle, Circle), circle_with_circle)
combine.add_rule((Square, Square), square_with_square)
combine.add_rule((Square, Circle),
         lambda s,c: circle_with_square(c,s))
# Enhancing base with triangle shape
class Triangle(Shape): pass
def triangle_with_triangle(triangle, triangle): ...
def triangle_with_circle(triangle, circle): ...
def triangle_with_square(triangle, square): ...
combine.add_rule((Triangle,Triangle), triangle_with_triangle)
combine.add_rule((Triangle,Circle), triangle_with_circle)
combine.add_rule((Triangle,Square), triangle_with_square)
combine.add_rule((Circle,Triangle),
         lambda c,t: triangle_with_circle(t,c))
combine.add_rule((Square,Triangle),
         lambda s,t: triangle_with_square(t,s))
# Use the rules in application
c, t, s = Circle(...), Triangle(...), Square(...)
newshape1 = combine(c, t)[0]
newshape2 = combine(s, c)[0]
# discover 'x' of unknown type, then combine with 't'
newshape3 = combine(t, x)[0]

上一页  1 2 3 4 5 6 7 8  下一页

Tags:Python 多元 泛化

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接