Python中的拷贝构造函数?

126 投票
8 回答
100659 浏览
提问于 2025-04-15 13:26

在Python里有没有复制构造函数?如果没有,我该怎么做才能实现类似的功能呢?

我的情况是,我在使用一个库,并且我对里面的一个类进行了扩展,增加了一些额外的功能。我想把从这个库里得到的对象转换成我自己类的实例。

8 个回答

26

这是我通常实现复制构造函数的一个简单例子:

import copy

class Foo:

  def __init__(self, data):
    self._data = data

  @classmethod
  def from_foo(cls, class_instance):
    data = copy.deepcopy(class_instance._data) # if deepcopy is necessary
    return cls(data)
46

在Python中,复制构造函数可以通过默认参数来定义。假设你想让普通构造函数运行一个叫做 non_copy_constructor(self) 的函数,而复制构造函数则运行 copy_constructor(self, orig)。那么你可以这样做:

class Foo:
    def __init__(self, orig=None):
        if orig is None:
            self.non_copy_constructor()
        else:
            self.copy_constructor(orig)
    def non_copy_constructor(self):
        # do the non-copy constructor stuff
    def copy_constructor(self, orig):
        # do the copy constructor

a=Foo()  # this will call the non-copy constructor
b=Foo(a) # this will call the copy constructor
88

我觉得你想要的是 copy模块

import copy

x = copy.copy(y)        # make a shallow copy of y
x = copy.deepcopy(y)    # make a deep copy of y

你可以像控制 pickle 一样来控制复制。

撰写回答