会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132824个问题
Python 全系列/第一阶段:Python入门/Python入门(动画版) 4143楼
Python 全系列/第一阶段:Python入门/函数和内存分析 4146楼
Python 全系列/第一阶段:Python入门/编程基本概念 4147楼
Python 全系列/第一阶段:Python入门/编程基本概念 4148楼
Python 全系列/第一阶段:Python入门/面向对象 4150楼

class ComputerFactory:
    _obj = None
    _init_flag = True

    def create_computer(self,brand):
        if brand == '联想':
           return Lenovo()
        elif brand == '华硕':
           return Asus()
        elif brand == '神舟':
            return Hasee()
        else:
            return '未知品牌,无法创建'

    def __new__(cls, *args, **kwargs):
        if cls._obj == None:
            cls._obj = object.__new__(cls)
        return cls._obj

    def __init__(self):
        if ComputerFactory._init_flag:
            print("init ComputerFactory....")
            ComputerFactory._init_flag = False


class Computer(ComputerFactory):
    def __init__(self,unit,amount):
        self.unit = unit
        self.amount = amount

    def calculate(self):
        print('总销售额是:{0}'.format(self.unit*self.amount))


class Lenovo(Computer):
    def __init__(self,unit,amount,year):
        self.year = year
        Computer.__init__(self,unit,amount)

    def calculate(self):
        print('第{0}年的总销售额是{1}'.format(self.year,self.unit*self.amount))

class Asus(Computer):
    def __init__(self, unit, amount, year):
        self.year = year
        Computer.__init__(self, unit, amount)

    def calculate(self):
        print('第{0}年的总销售额是{1}'.format(self.year, self.unit * self.amount))

class Hasee(Computer):
    def __init__(self, unit, amount, year):
        self.year = year
        Computer.__init__(self, unit, amount)

    def calculate(self):
        print('第{0}年的总销售额是{1}'.format(self.year, self.unit * self.amount))


factory = ComputerFactory()
c1 = factory.create_computer('联想')
c2 = factory.create_computer('华硕')
c3 = factory.create_computer('神舟')
print(c1)
print(c2)
print(c3)
l=Lenovo()
l.calculate('联想',3000,4789,2020)

老师好,最后想分别计算各个品牌的数据并打印输出,这里的代码不会写。

Python 全系列/第一阶段:Python入门/面向对象 4154楼
Python 全系列/第一阶段:Python入门/面向对象 4155楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637