Home:ALL Converter>TypeError: unsupported operand type(s) for *=

TypeError: unsupported operand type(s) for *=

Ask Time:2013-05-24T01:17:21         Author:Joseph Webber

Json Formatter

I'm teaching myself Python via an online wikibook, and came across a confusing error in one of the examples with overloading operators. According to the example:

class FakeNumber:
    n = 5
    def __add__(A,B):
        return A.n + B.n

c = FakeNumber()
d = FakeNumber()
d.n = 7

c.__imul__ = lambda B: B.n - 6
c *= d
c

is supposed to return:
1
but instead I get:
TypeError: unsupported operand type(s) for *=: 'FakeNumber' and 'FakeNumber'

I get that you can't multiply objects together, so then what is the point of c.__imul__ = lambda B: B.n - 6? Is there something missing, or where is there improper syntax?

Reference: http://en.wikibooks.org/wiki/Python_Programming/Classes#Operator_Overloading

Author:Joseph Webber,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/16720101/typeerror-unsupported-operand-types-for
Teisman :

Indeed the code is working as intended in python 2, but not in 3. A possible fix in python 3 would be the following:\n\nclass FakeNumber:\n def __init__(self, i):\n self.i = i\n\n def __imul__(self, B):\n self.i = self.i * B.i\n return self\n\na = FakeNumber(5)\nb = FakeNumber(6)\n\na *= b\n",
2013-05-23T21:33:39
yy