-2

this is a polynomial class

class Polynomial(object):

def __init__(self, polynomial):
    self.p = tuple(polynomial)

def get_polynomial(self):
    return self.p

def __neg__(self):
    return tuple([tuple([-i[j] if j==0 else i[j] for j in range(len(i))])for i in self.p])

def __add__(self, other):
    pass

def __sub__(self, other):
    pass

def __mul__(self, other):
    pass

def __call__(self, x):
    pass

def simplify(self):
    pass

def __str__(self):
    return 'something'

if i use the below code, i am getting error that -p has syntax error. is there a different way to override the magic methods ?

p = Polynomial([(2, 1), (1, 0)])
print p
print p.get_polynomial()
q = ‑p; q.get_polynomial()

i am getting syntax error at q = -p

RayMan
  • 1
  • 1

1 Answers1

3

The problem is that your __neg__ method returns a tuple, instead of an instance of your Polynomial class.

Thus when you try calling get_polynomial it will happen on a tuple, resulting in an error stating that tuple doesn't have a method called get_polynomial.

AttributeError: 'tuple' object has no attribute 'get_polynomial'

As such your __neg__ method must return an instance of your Polynomial class, like this:

def __neg__(self):
    return Polynomial([tuple([-i[j] if j == 0 else i[j] for j in range(len(i))]) for i in self.p])
vallentin
  • 23,478
  • 6
  • 59
  • 81