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

'''
    使用工厂模式、单例模式实现如下需求:
    (1) 电脑工厂类 ComputerFactory 用于生产电脑 Computer。工厂类使用单例模式,也就是说只能有一个工厂对象。
    (2) 工厂类中可以生产各种品牌的电脑:联想、华硕、神舟
    (3) 各种品牌的电脑使用继承实现:
    (4) 父类是 Computer 类,定义了 calculate 方法
    (5) 各品牌电脑类需要重写父类的 calculate
'''
class Computer():
    '''
        笔记本电脑父类
    '''
    def calculate(self):
        print("开始生产笔记本电脑...")

class ComputerFactory():
    '''
        工厂类
    '''
    __obj = None #类型
    __init_flag = True

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

    def createNotebook(self, flag):
        if flag == "lenovo" :
            return LianX()
        elif flag == "ASUS" :
            return HuoShuo()
        elif flag == "Hasee" :
            return ShenZ()
        else:return print("未知的品牌")

    def __new__(self, *args, **kwargs):
        if self.__obj == None:
            self.__obj = object.__new__(self)
            return self.__obj

class LianX(Computer):
    '''
        联想电脑
    '''
    def calculate(self):
        print("生产一台联想电脑...")

class HuoShuo(Computer):
    '''
        华硕电脑
    '''
    def calculate(self):
        print("生产一台华硕电脑...")

class ShenZ(Computer):
    '''
        神舟电脑
    '''
    def calculate(self):
        print("生产一台神舟电脑...")


com = ComputerFactory()
c = com.createNotebook("ASUS")
print(c.calculate())

lenovo = com.createNotebook("lenovo")
print(lenovo.calculate())

hasee = com.createNotebook("Hasee")
print(hasee.calculate())


老师,你看我的这个代码,为什么输出的时候会打印none

Snipaste_2022-04-04_14-47-59.png

Python 全系列/第一阶段:Python入门/面向对象 1670楼
Python 全系列/第一阶段:Python入门/编程基本概念 1671楼
Python 全系列/第一阶段:Python入门/编程基本概念 1672楼
Python 全系列/第一阶段:Python入门/面向对象 1673楼
Python 全系列/第一阶段:Python入门/面向对象 1674楼
Python 全系列/第一阶段:Python入门/面向对象 1675楼
Python 全系列/第一阶段:Python入门/面向对象 1676楼
Python 全系列/第一阶段:Python入门/编程基本概念 1678楼
Python 全系列/第一阶段:Python入门/Python入门(动画版) 1680楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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