How to copy python class?

deepcopy from copy does not copy the class:

 >>> class A(object): >>> ARG = 1 >>> B = deepcopy(A) >>> A().ARG >>> 1 >>> B().ARG >>> 1 >>> A.ARG = 2 >>> B().ARG >>> 2 

Is this just the way?

 B(A): pass 
+27
python
Mar 02 2018-12-12T00:
source share
6 answers

In general, inheritance is the right way, as other posters have noted.

However, if you really want to recreate the same type with a different name and without inheritance, you can do this as follows:

 class B(object): x = 3 CopyOfB = type('CopyOfB', B.__bases__, dict(B.__dict__)) b = B() cob = CopyOfB() print bx # Prints '3' print cob.x # Prints '3' bx = 2 cob.x = 4 print bx # Prints '2' print cob.x # Prints '4' 

You must be careful with variable attribute values:

 class C(object): x = [] CopyOfC = type('CopyOfC', C.__bases__, dict(C.__dict__)) c = C() coc = CopyOfC() cxappend(1) coc.x.append(2) print cx # Prints '[1, 2]' (!) print coc.x # Prints '[1, 2]' (!) 
+29
Nov 14
source share
β€” -

The correct way to "copy" a class, in your opinion, inherits:

 class B(A): pass 
+18
Mar 02 '12 at 22:15
source share

You can use the factory function:

 def get_A(): class A(object): ARG = 1 return A A = get_A() B = get_A() 
+6
Mar 03 2018-12-12T00:
source share

I think you misunderstand the value of a static variable here. Each time you declare a variable outside the method, and not in the form of self.some_thing , the variable will be considered as a static class variable (for example, your ARG variable). Thus, each object (instance) of a class that changes a static variable will lead to a change in all other objects in the same class. Actually this work really works.

+2
Apr 18 2018-12-18T00:
source share

Create your own constructor and just duplicate how you created your original class:

 class MyClass(object): def __init__(self, **kw): self.kw = kw self.__dict__.update(kw) def copy(self): return MyClass(**self.kw) 

I would try to avoid having to copy objects first.




sidenote: you can also get away from business:

 B = deepcopy(A) B.__dict__ = deepcopy(A.__dict__) 

But this is probably very wrong, and you should not do this. actually AttributeError: 'dictproxy' object has no attribute 'update' according to OP

0
Mar 02 2018-12-12T00:
source share

If you want to create only one instance of a class, simply execute it:

  >>> class A(object): ... ARG=1 ... >>> a = A() >>> A().ARG 1 >>> b = A() >>> b.ARG 1 >>> a.ARG=2 >>> b.ARG 1 
-one
Mar 02 '12 at 22:17
source share



All Articles