Reputation: 41
Im doing a class for polynomial and i have a problem with a copy function. It suppose to create a copy of the Poly object and return a reference to the new Poly object. Im really stuck on this copy idea. Thanks for any help
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)
I'm stuck on how to create a copy of the Poly object and return a reference to the new Poly object
Upvotes: 0
Views: 5334
Reputation: 894
Can you please elaborate why it doesn't work? This works perfectly for me:
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
Edit: Okay I see now he was passing in a list which was mutable is the general consensus.
Upvotes: 1
Reputation: 613
Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.
Check out copy module:
http://docs.python.org/library/copy.html
Upvotes: 2
Reputation: 6855
I think the problem you are having is that as self.a
is a list then you are passing a reference to that list in the instantiation of the new Poly object.
You should copy the list and give that copy to instantiate the object:
import copy
class Poly:
...
def copy(self):
return Poly(copy.copy(self.a))
Upvotes: 5
Reputation: 799082
The problem is actually hiding up in __init__()
.
self.a = p[:]
Upvotes: 2