在 python 中,后台究竟发生了什么使得 "x = 1j" 有效,但 "x = 1*j" 抛出错误?

In python, what exactly is going on in the background such that "x = 1j" works, but "x = 1*j" throws an error?

具体来说,如果我想定义一个对象,比如 z,这样

x = 1z

有效但

x = 1*z 

failed 抛出一个错误,我将如何定义这样一个对象?

我不认为它涉及重载乘法运算符。

1j,之所以有效,是因为它是 literal for a Complex Number(您在问题标题中提到了 1j)。有点像 [] 是列表的文字。

这是 Python 文档/规范的相关摘录:

Imaginary literals are described by the following lexical definitions:

imagnumber ::= (floatnumber | intpart) ("j" | "J")

An imaginary literal yields a complex number with a real part of 0.0. Complex numbers are represented as a pair of floating point numbers and have the same restrictions on their range. To create a complex number with a nonzero real part, add a floating point number to it, e.g., (3+4j).

换句话说,1j 是一个特例,您无法使 1z1j 那样工作。 1z 是一个 SyntaxError,仅此而已(就 Python 而言,就是这样)。