2012-04-19 41 views
0

我正在做一個多項式類,我有一個複製函數的問題。它假定創建Poly對象的副本並返回對新Poly對象的引用。我真的堅持這個副本的想法。感謝您的幫助python中的類定義中的複製函數

class Poly: 

    def __init__ (self, p): 
     self.a = p 
     self.deg= len(p) -1 
     if len(p) == 1 and p[0] == 0: 
      self.deg = -1 

    def evalPoly(self,x0): 
     ''' evaluates the polynomial at value x''' 
     b=0 
     for coefficients in reversed(self.a): 
      b=b*x0+int(coefficients) 
     return b 

    def polyPrime(self): 
     '''replaces the coeffiecients of self with the coefficients   
     of the derivative polynomial ''' 
     if self.deg == 0: 
      return np.zeroes(1,float), 0 
     else: 
      newdeg=self.deg-1 
      p=[i*self.a[i] for i in range(1,self.deg+1)] 
      p=str(p)[1: -1] 
      p=eval(p) 
     return p 

    def copy(self): 
     return Poly(self.a) 

我卡在如何創建多邊形對象的副本,並返回到新保利對象的引用

+2

究竟發生了什麼問題? – sinelaw 2012-04-19 22:22:28

回答

4

我想你所遇到的問題是,作爲self.a是一個列表,那麼你是路過新多邊形對象的實例化到該列表的引用。

您應該複製列表,並給該副本實例化對象:

import copy 

class Poly: 
    ... 
    def copy(self): 
     return Poly(copy.copy(self.a)) 
2

的問題實際上是在__init__()隱藏起來。

self.a = p[:] 
2

在Python賦值語句不復制的對象,他們創造的目標和對象之間的綁定。對於可變項目或包含可變項目的集合,有時需要副本,以便可以更改一個副本而不更改其他副本。

退房複製模塊:

http://docs.python.org/library/copy.html

1

能否請您詳細說明爲什麼它不工作?這對我來說是完美的:

class Poly(object): 

    def __init__ (self, p): 
     self.a = p 
     self.deg= len(p) -1 
     if len(p) == 1 and p[0] == 0: 
      self.deg = -1 

    def evalPoly(self,x0): 
     ''' evaluates the polynomial at value x''' 
     b=0 
     for coefficients in reversed(self.a): 
      b=b*x0+int(coefficients) 
     return b 

    def polyPrime(self): 
     '''replaces the coeffiecients of self with the coefficients   
     of the derivative polynomial ''' 
     if self.deg == 0: 
      return np.zeroes(1,float), 0 
     else: 
      newdeg=self.deg-1 
      p=[i*self.a[i] for i in range(1,self.deg+1)] 
      p=str(p)[1: -1] 
      p=eval(p) 
     return p 

    def __str__(self): 
     return "%s %s" % (self.a, self.deg) 

    def copy(self): 
     return Poly(self.a) 

if __name__ == "__main__": 
    p = Poly((1,3)) 
    print p 
    x = p.copy() 
    print x  

編輯:好吧,我現在看到他通過一個可變的列表是普遍的共識。