复数的“j”后缀如何工作?我可以制作自己的后缀吗?

How does the `j` suffix for complex numbers work? Can I make my own suffix?

我知道什么是复数以及它们在数学上是如何工作的,但是 如何让 python 知道 知道 它很复杂数字后的 j ?

>>> j
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'j' is not defined
>>> 1*j
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'j' is not defined
>>> 1j
1j
>>> 1j**2
(-1+0j)

我可以创建自己的后缀吗,比方说 p(严格正数)?

我可以做这样的事情吗?

>>> ... some weird stuff here ...
>>> p
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'p' is not defined
>>> 1*p
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'p' is not defined
>>> -1p
1p
>>> 0p
1p
>>> 

这是内置在Python语法中的,就像小数点一样,或者科学记数法中的e1e10等)。 j 使数字文字变为虚数。

Python 不允许您更改此设置。这并不意味着你不能——你可以修改语法——但那样的话语言就不再是Python。

Python 中允许的最接近的近似是通过实施运算符。

>>> class StrictlyPositive:
    def __rmatmul__(self, number):
        return abs(number)


>>> p = StrictlyPositive()
>>> -1@p
1

但是在做这样的事情时你必须注意运算符的优先级。为什么不直接使用内置 abs