首页 > 编程语言 >python 实现工厂类方法

python 实现工厂类方法

时间:2024-10-12 16:44:47浏览次数:1  
标签:__ python self 工厂 orange color print 方法 def


# 工厂类方法1,这些类的实例方法名 相同
class Fruit(object):
    def __init__(self):
        pass

    def print_color(self):
        pass

# 工厂类方法2
class Apple(Fruit):
    def __init__(self):
        pass

    def print_color(self):
        print("apple is in red")

# 工厂类方法3
class Orange(Fruit):
    def __init__(self):
        pass

    def print_color(self):
        print("orange is in orange")


# 管理类
class FruitFactory(object):
    fruits = {"apple": Apple, "orange": Orange}

    def __new__(cls, name):
        if name in cls.fruits.keys():
            return cls.fruits[name]()
        else:
            return Fruit()

fruit1 = FruitFactory("apple")
fruit2 = FruitFactory("orange")
fruit1.print_color()    # 输出: apple is in red 
fruit2.print_color()    # 输出: orange is in orange

标签:__,python,self,工厂,orange,color,print,方法,def
From: https://www.cnblogs.com/lanjianhua/p/18460839

相关文章

  • 一文了解Python反射机制(很详细)
    https://blog.csdn.net/weixin_40025666/article/details/134456717 https://www.cnblogs.com/mengdie1978/p/17425581.html 一、反射的概念python的反射机制,核心就是利用字符串去已存在的模块中找到指定的属性或方法,找到方法后自动执行——基于字符串的事件驱动。二、熟悉......
  • C# 使用反射机制适配多个不同供应商提供的可统一接口化的行为(方法)
    1、定义一个接口(IMedicareControlFee)定义行为;定义一个适配器(IMedicareControlFeeAdapter)可应对多厂商(多态);usingSystem;usingSystem.Diagnostics;usingSystem.IO;usingJetSun.Infrastructure;usingJetSun.Infrastructure.Services;usingMicrosoft.Practices.Unity;usi......
  • 一文弄懂 Python os.walk(),文件处理和目录遍历
    ......
  • python redis使用教程
    文章目录安装Redispython安装redis库使用Python连接Redis使用Redis实现缓存Redis中的常用缓存操作Redis缓存策略发布与订阅事务安装RedisRedisWindows最新安装教程(2024.10.10)python安装redis库pipinstallredisE:\Redis-x64-3.2.......
  • Python cachetools常用缓存算法汇总
    文章目录cachetools介绍缓存操作设置数据生存时间(TTL)自定义缓存策略缓存装饰器缓存清理cachetools超过缓存数量maxsizecachetools使用示例cachetools介绍cachetools:是一个Python第三方库,提供了多种缓存算法的实现。缓存是一种用于临时存储计算结果的技术,以......
  • 一种基于alpine、支持ARM架构64位的镜像构建方法及其构建系统
    本文分享自天翼云开发者社区《一种基于alpine、支持ARM架构64位的镜像构建方法及其构建系统》,作者:郑****团一种基于alpine、支持ARM架构64位的镜像构建方法及其构建系统,包括以下步骤:步骤1:准备arm64位基础镜像包在docker官网上下载对应arm64位python-arm-3.7.8-alpine基础镜像包......
  • python延时效果print逐个打印字符
    我想让python打印类似“正在加载。。。”,把每个句号逐个打印出来,并且它们之间的打印间隔睡眠时间0.5秒间隔实现方法:#!/bin/envpython#-*-coding:utf-8-*-importsysimporttimedefslow(msg,text):print(msg,end='')foriintext:print(i,end=''......
  • python中_init_.py 到底有啥用?
     1.__init__.py是个啥?__init__.py,这个文件名就是用来“初始化”的。在Python里,它主要用于标识一个目录是一个“包(Package)”。在项目里新建了一个文件夹,要让它成为一个可供导入的模块包,最简单的办法就是在里面加一个__init__.py。比如,咱们有个项目结构如下:my_project/......
  • Python中语法糖
    什么是语法糖?语法糖指简化语法,代码的基本逻辑没改变。语法糖代码示例squares_dict={}forxinrange(10):squares_dict[x]=x**2 列表推导简单的方式生成列表语法糖:squares_dict={x:x**2forxinrange(10)}输出:[0,1,4,9,......
  • 核密度估计 python代码
    确实,我提供的示例代码中有一些需要修正的地方。让我们逐一解决这些问题,并提供正确的核密度估计(KDE)的Python代码。使用SciPy进行核密度估计importnumpyasnpfromscipy.statsimportgaussian_kdeimportmatplotlib.pyplotasplt#生成一些随机数据data=np.random.no......