# coding: utf-8
class Geometricobject:
def __init__(self, color = "green", filled = "True"):
self.__color = color
self.__filled = filled
def getcolor(self):
return self.__color
def setcolor(self, color):
self.__color = color
def isfilled(self):
return self.__filled
def setfilled(self, filled):
self.__filled = filled
def __str__(self):
return "color: " + self.__color + \
" and filled: " + str(self.__filled)
# coding: utf-8
from GeometricObject import Geometricobject
import math
class Circle(Geometricobject):
def __init__(self, radius):
Geometricobject.__init__(self)
self.__radius = radius
def getRadius(self):
return self.__radius
def setRadius(self, radius):
self.__radius = radius
def getArea(self):
return self.__radius * self.__radius * math.pi
def getDiameter(self):
return 2 * self.__radius
def getPerimeter(self):
return 2 * self.__radius * math.pi
def printCircle(self):
print self.__str__() + "radius: " + str(self.__radius)
# Override the __str__() method defined in GeometricObject
def __str__(self):
return Geometricobject.__str__(self) + " radius: " + str(self.__radius)
from GeometricObject import Geometricobject
class Rectangle(Geometricobject):
def __init__(self, width = 1, height = 2):
Geometricobject.__init__(self)
self.__width = width
self.__height = height
def getWidth(self):
return self.__width
def setWidth(self, width):
self.__width = width
def getHeight(self, height):
return self.__height
def setHeight(self, height):
self.__height = height
def getArea(self):
return self.__width * self.__height
def getPerimeter(self):
return 2 * (self.__width + self.__height)
# Override the __str__ method defined in GeometricObject
def __str__(self):
return Geometricobject.__str__(self) + " width: " + \
str(self.__width) + " height: " + str(self.__height)
# coding: utf-8
from CircleFromGeometricObject import Circle
from RectangleFromGeometricObject import Rectangle
def main():
# Display circle and rectangle properties
c = Circle(4)
r = Rectangle(1, 3)
displayObject(c)
displayObject(r)
print "Are the circle and rectangle the same size? " , \
isSameArea(c, r)
# Display geometric object properties
def displayObject(g):
print g.__str__()
# Compare the areas of two geometric objects
def isSameArea(g1, g2):
return g1.getArea() == g2.getArea()
main()
在这个例子中,c是Circle类的一个对象。Circle类是GeometricObject类的子类。str()方法在这两个类中都有定义。因此,在displayObject方法中g应当调用哪个str()方法?g应当调用哪个str()方法由 动态绑定 决定。
动态绑定的机制如下: 假设对象o是类C1,C2,C3,…,Cn(C1是C2的子类,C2是C3的子类,… ,Cn-1 是 Cn 的子类,即Cn是通用的类,C1是最特定的类)的实例。在Python中,Cn是Object类。如果对象o调用一个方法p,那么Python会依次在类C1,C2,…,Cn中查找方法p的实现,直到找到为止。一旦找到一个实现,就会停止查找然后调用这个第一次找到的实现。