简体   繁体   English

在Python中将类分配给没有依赖性的变量

[英]Assign class to variable without dependencies in Python

I saw similar question here on stackoverflow but it wasn't satisfactorily answered. 我在这里在stackoverflow上看到了类似的问题,但没有得到令人满意的回答。 (link to this question - How to copy a python class? ) (链接到此问题- 如何复制python类?

So my question is, is there any possible way to create a copy of class (instance of a class), that is stored in variable A and assign this copy of class to new variable B without having these variables A and B mutually dependent? 所以我的问题是,是否有任何可能的方法来创建存储在变量A中的类的副本(类的实例),并将该类的副本分配给新变量B,而又不会使这些变量A和B相互依赖?

To be clear - is there a quite simple way? 要清楚-有没有很简单的方法?

Model situation would be: 模型情况为:

class B:
    def __init__(self, li):
        self.l = li * 5
        self.u = 5       

class A:
    def __init__(self):
        self.x = [1, 2, 3]
        self.c = B([45, 1, 3])
    self.i = 1

x = A()
y = x #This copies only reference to x

Implement __copy__() for your class, then you can use copy.copy() to create a copy of the instance. 为您的类实现__copy__() ,然后可以使用copy.copy()创建实例的副本。 This can't be done automatically due to the nature of Python objects (there is no way of knowing what variables will be set on an instance, and no way of knowing how it's been mutated, it's up to you to ensure that data is copied correctly). 由于Python对象的性质,无法自动完成此操作(无法知道将在实例上设置哪些变量,也无法知道如何对其进行了突变,这取决于您确保复制数据正确)。

Normally, presuming a class that functions in a normal way, __copy__() will probably be something simple like this for a supposed class SomeClass : 通常,假定一个正常工作的类,对于假定的类SomeClass__copy__()可能会像这样简单:

def __copy__(self):
    return SomeClass(self.somefield, self.otherfield, self.somethingelse)

Naturally, exact implementation will vary wildly based on the class itself. 自然,确切的实现将根据类本身而有很大的不同。

如果要创建对象的单独副本,请尝试使用copy模块

Using deepcopy in copy module is simpler. copy模块中使用deepcopy更简单。 Erm, guys here's solution to those subtle problems: http://docs.python.org/2/library/copy.html#copy.deepcopy 嗯,这里是解决那些细微问题的方法: http : //docs.python.org/2/library/copy.html#copy.deepcopy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM