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

Python用多元法泛化多态性

 2007-03-29 12:18:17 来源:WEB开发网   
核心提示: 改进继承多分派不仅仅泛化了多态性,它还在许多上下文中提供了更加灵活的继承方式,Python用多元法泛化多态性(5),这里举了一个示例,假定您正在编写处理各种形状的绘图或 CAD 程序;特别是,您希望能用某一种方式 合并两种形状,这种方式取决于所涉及的这两种形状

改进继承

多分派不仅仅泛化了多态性,它还在许多上下文中提供了更加灵活的继承方式。这里举了一个示例。假定您正在编写处理各种形状的绘图或 CAD 程序;特别是,您希望能用某一种方式 合并两种形状,这种方式取决于所涉及的这两种形状。而且,要研究的形状集将被派生的应用程序或插件扩展。扩展形状类的集合是一种笨拙的增强技术;例如:

清单 5. 用于功能扩展的继承

# Base classes
class Circle(Shape):
  def combine_with_circle(self, circle): ...
  def combine_with_square(self, square): ...
class Square(Shape):
  def combine_with_circle(self, circle): ...
  def combine_with_square(self, square): ...
# Enhancing base with triangle shape
class Triangle(Shape):
  def combine_with_circle(self, circle): ...
  def combine_with_square(self, square): ...
  def combine_with_triangle(self, triangle): ...
class NewCircle(Circle):
  def combine_with_triangle(self, triangle): ...
class NewSquare(Square):
  def combine_with_triangle(self, triangle): ...
# Can optionally use original class names in new context
Circle, Square = NewCircle, NewSquare
# Use the classes in application
c, t, s = Circle(...), Triangle(...), Square(...)
newshape1 = c.combine_with_triangle(t)
newshape2 = s.combine_with_circle(c)
# discover 'x' of unknown type, then combine with 't'
if isinstance(x, Triangle): new3 = t.combine_with_triangle(x)
elif isinstance(x, Square): new3 = t.combine_with_square(x)
elif isinstance(x, Circle): new3 = t.combine_with_circle(x)

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

Tags:Python 多元 泛化

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