Manually Clone/Copy an instance in Python
I know we have both c开发者_开发技巧opy
and deepcopy
inside the module copy
, but I'd like to do it manually...
I started by playing a little with __dict__
object just to see how can I create instances setting the same attributes that the object to be copied have, and here's the result of my first test:
class A(object):
def F(self):
print "Test!"
a = A()
x = type('A', (object, ), dict(A.__dict__))
x.F()
When executed, the following error appeared:
TypeError: unbound method F() must be called with A instance as first argument (got nothing instead)
How could I implement a method/function in Python to clone/copy (recursively) an object?
To manually create a shallow copy of an instance of the user-defined class A
, you can do
a = A()
b = object.__new__(A)
b.__dict__ = a.__dict__.copy() # or dict(a.__dict__)
The call to object.__new__()
creates a new instance without calling __init__()
.
Your code constructs a new type object rather than a new instance of A
.
Implementing a deep copy is much more involved -- you would basically need to reimplement the whole copy
and copyreg
modules. They are written in Python -- just follow the links to see the source code.
Without answering your "clone/copy" question, your code have a small bug. My version of your code is:
class A(object):
def f(self):
print "Test!"
a = A()
a.f()
X = type('A', (object, ), dict(A.__dict__))
x = X()
x.f()
精彩评论