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
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.
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.
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.
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]' (!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With