Python unsupported operand type TypeError:

Python unsupported operand type TypeError:

我一直在搞对象实例化。我不明白为什么这会在返回其身份时引发错误?

   >>> 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'

您创建了一个 class 的实例,并试图将该实例与一个数字相乘,您想要重载操作,请参阅下面的示例如何使用 Points 以正确的方式进行操作(您可以将其调整为你想用复数

做什么
class Point():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return "<Point x:{0},y:{1}>".format(self.x, self.y)

    # implement addition
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

    # implement subtraction
    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)

    # implement in-place addition
    def __iadd__(self, other):
        self.x += other.x
        self.y += other.y
        return self



    # Declare some points
    p1 = Point(10, 20)
    p2 = Point(30, 30)
    print(p1, p2)

    # Add two points
    p3 = p1 + p2
    print(p3)

    # subtract two points
    p4 = p2 - p1
    print(p4)

    # Perform in-place addition
    p1 += p2
    print(p1)

在您所做的具体实例中,您没有为您的 class 创建适当的 dunder 方法:

class Complex:
    def __init__(self, real, imaginary):
        print(f'Complex identity: {id(self)}')
        self.complex = f"{real} + {imaginary}i"
        self.real = real
        self.imaginary = imaginary

    def __mul__(self, input):
        if isinstance(input, int): #Just an example error type
            return f"{self.real*input} + {self.imaginary*input}i"
        else:
            raise Exception("TypeError: Not complex, real or imaginary")

if __name__ == "__main__":
    a = Complex(10,23)
    print(a*10)

这确实发生了,因为 python 对象是在变量赋值之前创建的。乘以 Complex 实例将引发异常,并且由于 right-hand 端的异常,变量 a 仍未创建。但在下面的示例中,显示了创建 Complex 实例的效果,并创建了变量 com,它返回对象的内存地址。但是,变量 a 尚未创建。 right-hand这边创建对象后,左边的变量绑定到对象上。变量只是标签。

>>> com = Complex()
Complex identity: 2660854433008
>>> com
<__main__.Complex object at 0x0000026B874884F0>
>>> 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'
 >>> dir()
['Complex', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'com']