python练习题,利用多态实现目标

python练习题,利用多态实现目标_第1张图片

利用控制台输入,进行租车计算
相关代码如下:

class Car:
    def __init__(self, name):
        self.name = name

    def price(self):
        pass


class Bieke(Car):
    def __init__(self, name, days):
        super().__init__(name)
        self.days = days

    def price(self):
        print("租用%s的天数是%d,价格是%d" % (self.name, self.days, 600 * self.days))


class Bwm(Car):
    def __init__(self, name, days):
        super().__init__(name)
        self.days = days

    def price(self):
        print("租用%s的天数是%d,价格是%d" % (self.name, self.days, 500 * self.days))


# 红旗1
class Hongq(Car):
    def __init__(self, name, days):
        super().__init__(name)
        self.days = days

    def price(self):
        print("租用%s的天数是%d,价格是%d" % (self.name, self.days, 300 * self.days))


# 金杯 <= 16人
class Jinbei(Car):
    def __init__(self, name, days):
        super().__init__(name)
        self.days = days

    def price(self):
        print("租用%s的天数是%d,价格是%d" % (self.name, self.days, 800 * self.days))


# 金龙 > 16人
class Jinglong(Car):
    def __init__(self, name, days):
        super().__init__(name)
        self.days = days

    def price(self):
        print("租用%s的天数是%d,价格是%d" % (self.name, self.days, 1500 * self.days))


def main():
    flag = True
    while flag:
        print("*" * 30)
        print("请选择车型:")
        print("1.小型车(4人座)")
        print("2.大型客车(4人以上)")
        size = int(input("请输入1/2:"))
        if size == 1:
            print("*" * 30)
            print("请选择车型:")
            print("1.别克GL8,600/天")
            print("2.宝马550i,500/天")
            print("3.红旗1,300/天")
            sizecar = int(input("请选择车型1/2/3:"))
            days = int(input("请输入使用天数:"))
            if sizecar == 1:
                c = Bieke("别克GL8", days)
                c.price()
            elif sizecar == 2:
                c = Bwm("宝马550i", days)
                c.price()
            elif sizecar == 3:
                c = Hongq("红旗1", days)
                c.price()
            else:
                print("输入有误~")
                continue
        elif size == 2:
            print("*" * 30)
            print("请选择车型:")
            print("1.金杯,16人及以下,800/天")
            print("2.金龙,16人以上,1500/天")
            sizecar2 = int(input("请选择车型1/2:"))
            days2 = int(input("请输入使用天数:"))
            if sizecar2 == 1:
                c = Jinbei("金杯", days2)
                c.price()
            elif sizecar2 == 2:
                c = Jinglong("金龙", days2)
                c.price()
            else:
                print("输入有误~")
                continue
        else:
            print("输入有误~")
            continue


if __name__ == "__main__":
    main()

你可能感兴趣的:(python练习题,利用多态实现目标)