Skip to main content
 首页 » 编程设计

python之__deepcopy__ 和在 __init__ 中改变参数的继承

2025年05月04日11jyk

当从基类继承时,它实现了__deepcopy__,而继承类改变了__init__中的参数,__deepcopy__如何从基类在继承类中重用?

举个例子:

class A(object): 
    def __init__(self, arg1, arg2): 
        self.arg1 = arg1 
        self.arg2 = arg2 
 
    def __deepcopy__(self, memo): 
        newone = type(self)(self.arg1, self.arg2) 
        ... 
 
class B(A): 
    def __init__(self, arg1): 
        A.__init__(self, arg1, None) 
 
    def __deepcopy__(self, memo): 
        newone = A.__deepcopy__(self, memo) # fails, because __deepcopy__ of 
                                            # A tries to create an instance of 
                                            # B with to many arguments 
        ... 

请您参考如下方法:

你可以通过接受任意数量的参数来解决这个问题,在你自己的构造函数中忽略它们:

class B(A): 
    def __init__(self, arg1, *ignored): 
        # `ignored` is.. ignored 
        A.__init__(self, arg1, None) 

既然你调用 A.__init__() 无论如何都将 None 作为第二个位置参数,那么在 __deepcopy__ 时忽略相同的参数是安全的> 再次将其传递回实例初始化程序。