2012-11-29 44 views
2

改變參數當從基類繼承,實現__deepcopy__和繼承類改變論據__init__,如何從基類的__deepcopy__可以在繼承類重用?__deepcopy__和繼承與__init__

下面的例子:

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 
     ... 

回答

1

你可以解決,通過接受的參數的任意數,忽略他們在自己的構造函數:

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

既然你叫A.__init__()None作爲無論如何,第二個位置參數,當__deepcopy__再次將它傳遞迴實例初始值設定項時,忽略相同的參數是安全的。

+0

謝謝,這對我來說工作得很好。 – Jester