Python 类的多态的运用

#类的多态的运用

#汽车类
class Car(object):
    def move(self):
        print("move ...")


#汽车商店类
class CarStore(object):
    
    #预定汽车
    def order(self,car_type):
        #注意,只有运行时,python才会检查是否存在selectCar()方法,意味着只要子类有这个方法就可以了,定义的时候,不写也是可以的,语法检查太差了
        return self.selectCar(car_type)
        
    #挑选汽车
    def selectCar(self):
        print("father function().. ")
    

#工厂类
class Factory(object):
    def createCar(self):
        pass
        
class BMWFactory(Factory):
    def createCar(self,car_type):
        if car_type == "BMW1":
            return BMW1Car()
        elif car_type == "BMW2":
            return BMW2Car()
        
#宝马汽车店
class BMW_CarStore(CarStore):
    #BMW_CarStore继承了CarStore,CarStore中有selectCar方法,但是两者函数签名都不一样,python仍然重写了这个方法
    #通过测试,直接调用selectCar(void),提示没有这个方法,说明虽然函数签名不同,但是selectCar(()方法的确重写了
    def selectCar(self,car_type):
        return BMWFactory().createCar(car_type)
        
            
#宝马型号1
class BMW1Car(Car):
    pass

#宝马型号2
class BMW2Car(Car):
    pass

    

store = BMW_CarStore()

#报错
#store.selectCar()

car = store.order("BMW1")

car.move()

猜你喜欢

转载自www.cnblogs.com/zhanggaofeng/p/9609729.html