copy.deepcopy raises TypeError on objects with self-defined __new__() method

后端 未结 3 1687
盖世英雄少女心
盖世英雄少女心 2021-01-17 20:42

I want to implement a symbol type, which keeps track of the symbols we already have(saved in _sym_table), and return them if they exist, or create new ones othe

3条回答
  •  既然无缘
    2021-01-17 20:48

    one problem is that deepcopy and copy have no way of knowing which arguments to pass to __new__, therefore they only work with classes that don't require constructor arguments.

    the reason why you can have __init__ arguments is that __init__ isn't called when copying an object, but __new__ must be called to create the new object.

    so if you want to control copying, you'll have to define the special __copy__ and __deepcopy__ methods:

    def __copy__(self):
        return self
    
    def __deepcopy__(self, memo):
        return self
    

    by the way, singletons are evil and not really needed in python.

提交回复
热议问题