I've been trying to follow a video tutorial on Python and cannot understand one operation the developer performs.
class Polynomial():
def __init__(self, *coeffs):
self.coeffs = coeffs # (3,4,3)
def __repr__(self):
return 'Polynomial(*{!r})'.format(self.coeffs)
def __add__(self, other):
print(self.coeffs)
print(other.coeffs)
z = (x + y for x, y in zip(self.coeffs, other.coeffs))
print(z)
return Polynomial(*(x + y for x, y in zip(self.coeffs, other.coeffs)))
p1 = Polynomial(1, 2, 3) # x^2 + 2x + 3
p2 = Polynomial(3, 4, 3) # 3x^2 + 4x + 3
#print(p2) # Polynomial(*(3, 4, 3))
print(p1 + p2) # Polynomial(*(4, 6, 6))
The above example will print
<generator object Polynomial.__add__.<locals>.<genexpr> at 0x030D0390>
as the return value of z, I cannot understand why because I am performing a zip operation of two tuples?
Alongside that problem, I do not understand why removing the *
during the return of __add__
causes a problem i.e return Polynomial(*(x + y for x, y in zip(self.coeffs, other.coeffs)))
to return Polynomial((x + y for x, y in zip(self.coeffs, other.coeffs)))
What is the * operator doing, and why is z an object of Polynomial?
The _add__
method does not contain a parameter containing a *
or **
and is therefore a different situation.