Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Specifically, if I wanted to define an object, say z, such that

x = 1z

worked but

x = 1*z 

failed threw an error, how would I define such an object?

I don't think it involves overloading the multiplying operator.

like image 721
user2635263 Avatar asked Dec 14 '22 15:12

user2635263


1 Answers

1j, works because it's a literal for a Complex Number (you mentioned 1j in your question title). Kind of like [] is a literal for a list.

Here's the relevant excerpt from the Python docs / spec:

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).

In other words, 1j is a special case, and there's nothing you can do to make 1z work like 1j does. 1z is a SyntaxError, and that's it (as far as Python is concerned, that is).

like image 159
Thomas Orozco Avatar answered Apr 09 '23 07:04

Thomas Orozco