Home:ALL Converter>Python unsupported operand type TypeError:

Python unsupported operand type TypeError:

Ask Time:2022-02-04T14:56:48         Author:Richard

Json Formatter

I have been messing around with object instantiation. I don't understand why this is raising errors while returning its identity?

   >>> class Complex:
    ...     def __init__(self):
    ...         print(f'Complex identity: {id(self)}' )
    ...

>>> a = Complex() * 27
Complex identity: 2660854434064
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'Complex' and 'int'

Author:Richard,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/70982502/python-unsupported-operand-type-typeerror
Nir Elbaz :

You create an instance of a class and trying to multiply the instance with a number ,You want to do overloading of operations,see an example below how to do it the proper way with Points(You can adjust it to what you want to do with Complex number\nclass Point():\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __repr__(self):\n return "<Point x:{0},y:{1}>".format(self.x, self.y)\n\n # implement addition\n def __add__(self, other):\n return Point(self.x + other.x, self.y + other.y)\n\n # implement subtraction\n def __sub__(self, other):\n return Point(self.x - other.x, self.y - other.y)\n\n # implement in-place addition\n def __iadd__(self, other):\n self.x += other.x\n self.y += other.y\n return self\n\n\n\n # Declare some points\n p1 = Point(10, 20)\n p2 = Point(30, 30)\n print(p1, p2)\n\n # Add two points\n p3 = p1 + p2\n print(p3)\n\n # subtract two points\n p4 = p2 - p1\n print(p4)\n\n # Perform in-place addition\n p1 += p2\n print(p1)\n",
2022-02-04T07:09:49
kibromhft :

This is actually happening because python objects are created before variable assignments. Multiplying a Complex instance will raise an exception and the variable a remained uncreated because of the exception on the right-hand side. But in the following example, the effect of creating a Complex instance is shown and the variable com is created, which is returning the memory address of the object. However, the variable a is not yet created. The variable on the left is bound to the object after the object is created on the right-hand side. Variables are just labels.\n>>> com = Complex()\nComplex identity: 2660854433008\n>>> com\n<__main__.Complex object at 0x0000026B874884F0>\n>>> a = Complex() * 27\nComplex identity: 2660854434064\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nTypeError: unsupported operand type(s) for *: 'Complex' and 'int'\n >>> dir()\n['Complex', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'com']\n",
2022-02-04T07:29:41
yy