#对于弱类型的语言来说, 变量没有申明类型,因此同一个变量完全可以再不同的事件引用不同的对象,当同一个变量再调用同一个方法时候,完全可以呈现出多种行为 #这就是多态 #DrawCanvas的draw_canvas方法传入一个shape参数,该方法就是调用shape参数的draw方法,将自己绘制再画布上 class DrawCanvas: def draw_canvas(self,shape): shape.draw(self) class Rectangle: def draw(self,canvas): print ("draw rectangle in %s" % canvas) class Triangle: def draw(self,canvas): print "draw triangle in %s" % canvas class Circle: def draw(self,canvas): print "draw circle in %s" % canvas c = DrawCanvas() c.draw_canvas(Rectangle()) c.draw_canvas(Triangle()) c.draw_canvas(Circle())
draw rectangle in <__main__.DrawCanvas instance at 0x0000000003815B88> draw triangle in <__main__.DrawCanvas instance at 0x0000000003815B88> draw circle in <__main__.DrawCanvas instance at 0x0000000003815B88>