首页 > 编程语言 >Python: Prototype Pattern

Python: Prototype Pattern

时间:2022-10-20 22:04:40浏览次数:29  
标签:some copy Python Pattern list objects component copied Prototype

DuPrototype.py

import copy

## 原型模式 Prototype Pattern  DuPrototype。py
class SelfReferencingEntity:
    def __init__(self):
        self.parent = None

    def set_parent(self, parent):
        self.parent = parent


class SomeComponent:
    """
    Python provides its own interface of Prototype via `copy.copy` and
    `copy.deepcopy` functions. And any class that wants to implement custom
    implementations have to override `__copy__` and `__deepcopy__` member
    functions.
    """

    def __init__(self, some_int, some_list_of_objects, some_circular_ref):
        self.some_int = some_int
        self.some_list_of_objects = some_list_of_objects
        self.some_circular_ref = some_circular_ref

    def __copy__(self):
        """
        Create a shallow copy. This method will be called whenever someone calls
        `copy.copy` with this object and the returned value is returned as the
        new shallow copy.
        """

        # First, let's create copies of the nested objects.
        some_list_of_objects = copy.copy(self.some_list_of_objects)
        some_circular_ref = copy.copy(self.some_circular_ref)

        # Then, let's clone the object itself, using the prepared clones of the
        # nested objects.
        new = self.__class__(
            self.some_int, some_list_of_objects, some_circular_ref
        )
        new.__dict__.update(self.__dict__)

        return new

    def __deepcopy__(self, memo=None):
        """
        Create a deep copy. This method will be called whenever someone calls
        `copy.deepcopy` with this object and the returned value is returned as
        the new deep copy.

        What is the use of the argument `memo`? Memo is the dictionary that is
        used by the `deepcopy` library to prevent infinite recursive copies in
        instances of circular references. Pass it to all the `deepcopy` calls
        you make in the `__deepcopy__` implementation to prevent infinite
        recursions.
        """
        if memo is None:
            memo = {}

        # First, let's create copies of the nested objects.
        some_list_of_objects = copy.deepcopy(self.some_list_of_objects, memo)
        some_circular_ref = copy.deepcopy(self.some_circular_ref, memo)

        # Then, let's clone the object itself, using the prepared clones of the
        # nested objects.
        new = self.__class__(
            self.some_int, some_list_of_objects, some_circular_ref
        )
        new.__dict__ = copy.deepcopy(self.__dict__, memo)

        return new

  

main.py

调用:

       ## 原型模式 Prototype Pattern
list_of_objects = [1, {1, 2, 3}, [1, 2, 3]]
circular_ref = DuPrototype.SelfReferencingEntity()
component = DuPrototype.SomeComponent(23, list_of_objects, circular_ref)
circular_ref.set_parent(component)

shallow_copied_component = copy.copy(component)

# Let's change the list in shallow_copied_component and see if it changes in
# component.
shallow_copied_component.some_list_of_objects.append("另一个对象")
if component.some_list_of_objects[-1] == "另一个对象":
     print(
          "向shallow_copied_component添加元素 "
          "some_list_of_objects 添加到组件中"
          "some_list_of_objects."
     )
else:
     print(
          "向shallow_copied_component添加元素 "
          "some_list_of_objects 不会将它添加到组件中"
          "some_list_of_objects."
     )

# Let's change the set in the list of objects.
component.some_list_of_objects[1].add(4)
if 4 in shallow_copied_component.some_list_of_objects[1]:
     print(
          "更改组件的 some_list_of_objects中的对象 "
          "在“shallow_copied_component”中更改该对象 "
          "some_list_of_objects."
     )
else:
     print(
          "更改组件的 some_list_of_objects中的对象 "
          "不会改变“shallow_copied_component”中的对象 "
          "some_list_of_objects."
     )

deep_copied_component = copy.deepcopy(component)

# Let's change the list in deep_copied_component and see if it changes in
# component.
deep_copied_component.some_list_of_objects.append("一个对象")
if component.some_list_of_objects[-1] == "一个对象":
     print(
          "向`deep_copied_component` 中添加元素 "
          "some_list_of_objects将它添加到组件中"
          "some_list_of_objects."
     )
else:
     print(
          "向`deep_copied_component`中添加元素 "
          "some_list_of_objects添加不到组件中"
          "some_list_of_objects."
     )

# Let's change the set in the list of objects.
component.some_list_of_objects[1].add(10)
if 10 in deep_copied_component.some_list_of_objects[1]:
     print(
          "挂起组件的some_list_of_objects中的对象 "
          "在“deep_copied_component”中更改该对象 "
          "some_list_of_objects."
     )
else:
     print(
          "挂起组件的some_list_of_objects中的对象 "
          "在“deep_copied_component”中更改不了该对象"
          "some_list_of_objects."
     )

print(
     f"id(deep_copied_component.some_circular_ref.parent): "
     f"{id(deep_copied_component.some_circular_ref.parent)}"
)
print(
     f"id(deep_copied_component.some_circular_ref.parent.some_circular_ref.parent): "
     f"{id(deep_copied_component.some_circular_ref.parent.some_circular_ref.parent)}"
)
print(
     "^^ 这表明深度复制对象包含相同的引用,它们 "
     "不重复克隆。"
)

  

输出:

 

向shallow_copied_component添加元素 some_list_of_objects 添加到组件中some_list_of_objects.


更改组件的 some_list_of_objects中的对象 在“shallow_copied_component”中更改该对象 some_list_of_objects.


向`deep_copied_component`中添加元素 some_list_of_objects添加不到组件中some_list_of_objects.


挂起组件的some_list_of_objects中的对象 在“deep_copied_component”中更改不了该对象some_list_of_objects.


id(deep_copied_component.some_circular_ref.parent): 2246621676496
id(deep_copied_component.some_circular_ref.parent.some_circular_ref.parent): 2246621676496
^^ 这表明深度复制对象包含相同的引用,它们 不重复克隆。

Process finished with exit code 0

  

标签:some,copy,Python,Pattern,list,objects,component,copied,Prototype
From: https://www.cnblogs.com/geovindu/p/16811449.html

相关文章

  • Python学习三天计划-1
    一、第一个Python程序配置好环境变量后打开CMD(命令提示符)程序,输入Python并回车然后,在里面输入代码回车即可立即执行Python解释器的作用是将Python代码翻译成计算机......
  • 2.6 利用Python读写文件中的内容
    #读取文件内容f=open('note.txt','r',encoding='utf-8')#有中文使用encoding='utf-8'text=f.readlines()print(text)f.close()#推荐的使用的方式with...as上下......
  • python内置模块:os、sys、json
    目录一、os模块1os.mkdir()和os.makedirs()创建目录(文件夹)1.mkdir()可以创建单机目录2.makedirs()可以创建单级目录和多级目录2os.rmdir()和os.makedi......
  • Python学习路程——Day19
    Python学习路程——Day19os模块1、os.mkdir() 创建目录(文件夹)'''语法结构: importos os.mkdir() os.makedirs()r的作用是让\起作用'''importosos.mkdir(r......
  • python 图形的数据处理 (折线图为例)
    1.通过json模块对数据进行处理ab173.com是懒人工具-json在线解析,可以通过他对json数据进行格式化的分析。"""演示可视化需求1:折线图开发"""importjsonfrompyec......
  • python进阶之路18 os、sys、json模块
    os模块与sys模块os模块主要与操作系统打交道sys模块主要与python解释器打交道os模块(重要)os模块主要与代码运行所在的操作系统打交道importos#1.创建目录(......
  • 吐血整理python数据分析利器pandas的八个生命周期!
    这里从八个pandas的数据处理生命周期,整理汇总出pandas框架在整个数据处理过程中都是如何处理数据的。【阅读全文】也就是从pandas的数据表对象以及数据汇总、数据统计等......
  • python(os模块)
    模块os模块(重要)os模块是python中这里文件和目录最常用的模块,该模块提供了非常丰富的方法用来处理文件和目录。创建文件夹​ os.mkdir():创建一个新的文件夹(目录......
  • 【Python】【爬虫】爬取小说5000章,遇到的爬虫问题与解决思路
    爬虫问题分析回顾之前写了一个爬取小说网站的多线程爬虫,操作流程如下:先爬取小说介绍页,获取所有章节信息(章节名称,章节对应阅读链接),然后使用多线程的方式(pool=Pool(50)),......
  • python self.__dict__.update 批量更新属性的使用
    首先我们回顾下字典的update方法,以及查看对象属性__dict__的使用;然后再看对象.__dict__update的使用 一、字典的update方法1.描述dict.update()update()函数把字典di......