会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132437个问题
Python 全系列/第一阶段:Python入门/控制语句 4052楼
Python 全系列/第一阶段:Python入门/编程基本概念 4053楼
Python 全系列/第一阶段:Python入门/函数和内存分析 4054楼

#设计模式:工厂模式的测试

class Computerfactory:
    __obj = None
    __init_flag = True

    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.__init_flag = False

    def creat(self,brand):
        if brand == "联想":
            return LX(Computer)
        elif brand == "华硕":
            return HS(Computer)
        elif brand == "神舟":
            return SZ(Computer)
        else:
            return "未知品牌,无法生产"

class Computer:
    def __init__(self,brand):
        self.brand = brand

    def calculate(self):
        print("电脑生产完成!")


class LX(Computer):

    def __init__(self,brand):
        Computer.__init__(self,brand)

    def calculate(self):
        print("{0}牌电脑生产完毕,等待验收...".format(self.brand))

class HS(Computer):

    def __init__(self, brand):
        Computer.__init__(self, brand)

    def calculate(self):
        print("{0}牌电脑生产完毕,等待验收...".format(self.brand))

class SZ(Computer):

    def __init__(self, brand):
        Computer.__init__(self, brand)

    def calculate(self):
        print("{0}牌电脑生产完毕,等待验收...".format(self.brand))

factory = Computerfactory()
c1 = factory.creat("联想")
c1.calculate()
print(c1)
c2 = factory.creat("华硕")
c2.calculate()
print(c2)
factory2 = Computerfactory()
print(factory)
print(factory2)

运行结果如下:

init......
<class '__main__.Computer'>牌电脑生产完毕,等待验收...
<__main__.LX object at 0x000001D5F4FC8C40>
<class '__main__.Computer'>牌电脑生产完毕,等待验收...
<__main__.HS object at 0x000001D5F4FC88B0>
<__main__.Computerfactory object at 0x000001D5F4FC8C70>
<__main__.Computerfactory object at 0x000001D5F4FC8C70>

为什么牌字前面没法输出对应的电脑品牌名?

Python 全系列/第一阶段:Python入门/面向对象 4056楼
Python 全系列/第一阶段:Python入门/面向对象 4058楼
Python 全系列/第一阶段:Python入门/面向对象 4059楼
Python 全系列/第一阶段:Python入门/Python入门(动画版) 4065楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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