0

多項式のクラスを行っていますが、コピー機能に問題があります。Poly オブジェクトのコピーを作成し、新しい Poly オブジェクトへの参照を返すとします。私はこのコピーのアイデアに本当にこだわっています。助けてくれてありがとう

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)

Poly オブジェクトのコピーを作成し、新しい Poly オブジェクトへの参照を返す方法に行き詰まっています。

4

4 に答える 4

5

あなたが抱えている問題self.aは、リストのように、新しい Poly オブジェクトのインスタンス化でそのリストへの参照を渡していることだと思います。

リストをコピーし、そのコピーを渡してオブジェクトをインスタンス化する必要があります。

import copy

class Poly:
    ...
    def copy(self):
        return Poly(copy.copy(self.a))
于 2012-04-19T22:27:16.513 に答える
2

問題は実際には に隠れてい__init__()ます。

    self.a = p[:]
于 2012-04-19T22:26:14.797 に答える
2

Python の割り当てステートメントはオブジェクトをコピーせず、ターゲットとオブジェクトの間のバインディングを作成します。変更可能なコレクションまたは変更可能なアイテムを含むコレクションの場合、1 つのコピーを変更せずに他のコピーを変更できるように、コピーが必要になることがあります。

コピー モジュールをチェックアウトします。

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

于 2012-04-19T22:28:34.017 に答える
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    

編集:わかりました、彼は変更可能なリストを渡していたことが一般的なコンセンサスです。

于 2012-04-19T22:32:11.350 に答える