修改现有 class,可变对象的深度复制给出相同的 id

Modify existing class, deepcopy of mutable object gives same id

我正在尝试修改现有的 class。
现有的 class 应该保持不变。

from functools import wraps
from copy import deepcopy


class OldClass(object):

    def method1(self, *args, **kwargs):
        print("Method1")


def wrap_cls():
    class_deepcopy = deepcopy(OldClass)
    orig_method = class_deepcopy.method1

    @wraps(orig_method)
    def new_method1(self, *args, **kwargs):
        orig_method(self, *args, **kwargs)
        print('Method changed!')

    class_deepcopy.method1 = new_method1

    # OldClass is changed, as id(OldClass) == id(class_deepcopy)?
    print("id(old) == id(new): {}".format(
        id(OldClass) == id(class_deepcopy)
    ))

    return class_deepcopy


WrappedCls = wrap_cls()

a = OldClass()
a.method1()

输出是

id(old) == id(new): True
method1
Method changed!

`

这表示使用OldClass而不是WrappedCls。这是因为 wrap_cls() 方法中的 deepcopy(OldClass) 不起作用:
它 return 是一个与旧 class.

具有相同 ID 的对象

所以我要在这里提问:
为什么 deepcopy(OldClass) return 与 OldClass 具有相同 ID 的对象?
如何在运行时修改 classes?

Why…?

This module does not copy types like module, method, …, array, or any similar types. It does “copy” functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the pickle module.

How can I modify classes at runtime?
(就像你开始的方式(“元编程”)。)
要保留先前存在的(“原始”)class 不变:
一)Derive a class from the pre-existing one

d) 创建工厂方法并修改instances