Python面向对象编程-继承
继承是面向对象的重要特性之一。继承是相对两个类而言的父子关系,子类继承了父类所以的公共特性。继承实现了代码的重用。Python不提供过度的包装,所以封装性在Python程序中体现得比较弱,实际上继承和多态已经足够好用。
下面就是Python程序中最简单的继承例子:
#!/usr/bin/env python
class Fruit:
def __init__(self,color):
self.color = color
print "fruit's color:%s"% self.color
def grow(self):
print "grow..."
class Apple(Fruit):
def __init__(self,color):
Fruit.__init__(self,color)
print "apple's color:%s"% self.color
class Banana(Fruit):
def __init__(self,color):
Fruit.__init__(self,color)
print "banana's color:%s"% self.color
def grow(self):
print "banana grow..."
if __name__ == "__main__":
apple = Apple("red")
apple.grow()
banana = Banana("yellow")
banana.grow()