如何在 python 中复制未初始化的 class

How to copy an uninitialized class in python

我有这个class

class TestEvent(object)
    value = None

我想得到这个 class 的副本,所以它没有被引用,但是当我尝试使用复制库时,变量总是被引用:

>>> clsOne = TestEvent
>>> clsTwo = copy.deepcopy(TestEvent)
>>> clsOne.value = "hello motto"
>>> clsTwo.value
"hello motto"

copy.copy也是如此。有人可以告诉我如何得到这个 class 的副本吗?

copy.copy() 和朋友将 return 当您传递 class 时值不变。

您可以使用 type() 代替:

# shallow copy of the namespace
new_cls = type(cls.__name__, cls.__bases__, dict(cls.__dict__))

或:

# deep copy of the namespace
new_cls = type(cls.__name__, cls.__bases__, copy.deepcopy(dict(cls.__dict__)))