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 中的赋值语句不复制对象,它们在目标和对象之间创建绑定。对于可变或包含可变项的集合,有时需要一个副本,以便可以更改一个副本而不更改另一个副本。

查看复制模块:

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 回答