Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a python class?

Tags:

python

deepcopy from copy does not copy a class:

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

Is it only way?

B(A):     pass 
like image 442
I159 Avatar asked Mar 02 '12 22:03

I159


People also ask

How do I copy a class in Python?

In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object.

What does Copy () do in Python?

Copy List Python: copy() Method. The Python copy() method creates a copy of an existing list. The copy() method is added to the end of a list object and so it does not accept any parameters. copy() returns a new list.

How do you copy code in Python?

To copy text to the clipboard, pass a string to pyperclip. copy() . To paste the text from the clipboard, call pyperclip. paste() and the text will be returned as a string value.


1 Answers

In general, inheritance is the right way to go, as the other posters have already pointed out.

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

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

You have to be careful with mutable attribute values:

class C(object):     x = []  CopyOfC = type('CopyOfC', C.__bases__, dict(C.__dict__))  c = C() coc = CopyOfC()  c.x.append(1) coc.x.append(2)  print c.x   # Prints '[1, 2]' (!) print coc.x # Prints '[1, 2]' (!) 
like image 156
Florian Brucker Avatar answered Oct 10 '22 23:10

Florian Brucker