deepcopy从copy不会复制一个类:
deepcopy
copy
>>> class A(object): >>> ARG = 1 >>> B = deepcopy(A) >>> A().ARG >>> 1 >>> B().ARG >>> 1 >>> A.ARG = 2 >>> B().ARG >>> 2
是唯一的办法吗?
B(A): pass
通常,继承是正确的方法,正如其他发布者已经指出的那样。
但是,如果您确实想重新创建具有不同名称且没有继承的相同类型,则可以这样进行:
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'
您必须注意可变属性值:
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]' (!)