zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    noip模拟赛 软件software
    bzoj1070: [SCOI2007]修车
    bzoj2947: [Poi2000]促销
    bzoj2940: [Poi2000]条纹
    bzoj3714: [PA2014]Kuglarz
    bzoj3717: [PA2014]Pakowanie
    说明
    Hello World!
    牛客网PAT练兵场-旧键盘打字
    牛客网PAT练兵场-锤子剪刀布
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/9609729.html
Copyright © 2011-2022 走看看