python中的多态
动态多态是指发出同样的消息被不同的对象接收时,可能导致完全不同的行为。因此, 在用户不做任何干预的情况下,类的成员函数的行为能够根据调用他的对象类型,自动作出适应性调整,而且调整时发生在程序运行时。
多态演示如下:
class Fruit:
def __init__(self, color = None):
self.color = color
class Apple(Fruit):
def __init__(self, color = "red"):
Fruit.__init__(self, color)
class Banana(Fruit):
def __init__(self, color = "yellow"):
Fruit.__init__(self, color)
class FruitShop:
def sellFruit(self, fruit):
if isinstance(fruit, Apple): #函数isinstance是用来判断fruit的类型
print "sell apple"
if isinstance(fruit, Banana):
print "sell banana"
if isinstance(fruit, Fruit):
print "sell fruit"
if __name__ == "__main__" :
shop = FruitShop()
apple = Apple("red")
banana = Banana("yellow")
shop.sellFruit(apple) #输出: sell fruit sell apple
shop.sellFruit(banana) # 输出: sell fruit sell banana
多重继承
python也支持多重继承,即一个类有多个父类。因此子类同时具有两个父类的属性。
多继承演示如下:
class Fruit(object):
def __init__(self):
print "initialize Fruit"
def grow(self):
print "grow..."
class Vegetable(object):
def __init__(self):
print "initialize Vegetable"
def plant(self):
print "plant..."
class Watermelon(Vegetable, Fruit):
pass
if __name__ == "__main__":
w = Watermelon() #输出:initialize Vegetable(只继承
了第一个 父类的__init__方法)
w.grow() #输出: grow...
w.plant() #输出: plant...
运算符重载
运算符重载用于表达式的计算,,自定义的对象不能进行计算,运算符重载可以实现对象之间的运算。python把运算符和类的内置方法关联起来,每个运算符都对应一个函数。
运算符重载演示如下:
class Fruit:
def __init__(self, price = 0):
self.price = price
def __add__(self, other): #运算符重载
return self.price + other.price
def __gt__(self, other):
if self.price > other.price:
flag = True
else:
flag = False
return flag
class Apple(Fruit):
pass
class Banana(Fruit):
pass
if __name__ == "__main__":
apple = Apple(3)
print "苹果的价格:", apple.price #输出: 3
banana = Banana(2)
print "香蕉的价格:", banana.price #输出: 2
print apple > banana #输出: True
total = apple + banana
print "总计:", total #输出: 5
阅读(1637) | 评论(0) | 转发(0) |