【问题标题】:prevent deep copy on python防止在 python 上进行深度复制
【发布时间】:2021-04-03 10:41:57
【问题描述】:

问题如下:假设你有一个类'P'(在python上定义),包含一些参数,你想通过你的主代码传递给你代码中的不同对象。

有什么方法可以防止在主类上创建的类 P 的实例 p 被“深度复制”到代码中? (理想情况下,没有其他模块可以实例化类 P 的元素,例如,最多强制类的实例,在 python 上是否有一种简短的方法可以做到这一点?)。

目的是动态改变实例P的参数,在主代码上(仅),并将修改转移到整个代码,而不需要额外的手动设置。

【问题讨论】:

    标签: python design-patterns deep-copy


    【解决方案1】:

    最后,我回答了我自己的问题,我认为它应该可以解决问题(但如果有更pythonic和更简单的方法..我很想知道): 包含类 P 的模块 p

    class P(object):
        instance = None
        nb_instance = 0
        def __init__(self, **params):
            assert type(self).instance is None, "no more than one instance of P is possible"
            self.params = params
            type(self).instance = self
            type(self).nb_instance +=1
    
        def __deepcopy__(self,el):
            assert 1==0, "no deep copy of P is possible"
    
        def __copy__(self):
            assert 1==0, "no shallow copy of P is possible"
    

    另一个尝试从类 P 实例化新元素的模块

    import p
    
    
    class OtherCode(object):
        def __init__(self):
            self.a = 1
            self.p = p.P(sigma=4.0,mu=1.0)
    
    

    最后是要运行的主要代码

    import p,otherCode
    import copy
    if __name__ == '__main__':
        P1 = p.P(sigma=0.1,mu=1.0)
        #o =otherCode.OtherCode()
        try:
            P2 = copy.deepcopy(P1)
        except Exception as E:
            print(E)
        try:
            P3 = copy.copy(P1)
        except Exception as E:
            print(E)
        try:
            otherCode.OtherCode()
        except Exception as E:
            print(E)
        P5 = P1
    
        print("P1 is P5 {}".format(P1 is P5))
    
    The output:
    no deep copy of P is possible
    no shallow copy of P is possible
    no more than one instance of P is possible
    P1 is P5 True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-29
      • 2011-09-25
      • 2019-10-22
      • 2014-09-05
      • 1970-01-01
      • 2018-10-08
      • 2013-12-03
      • 1970-01-01
      相关资源
      最近更新 更多