简体   繁体   中英

Is there a possibility to override a unary operator with a binary one in Python?

I tried to define a class and override the tilde operator:

class foo:
    def __invert__(self, other)
        return 1232 # a random number , just as test

Then calling it like:

>>> f = foo()
>>> g = foo()
>>> f ~ g
  File "<input>", line 1
    f ~ g
      ^
SyntaxError: invalid syntax

Can we replace the tilde operator with a binary one so we can do an operation like f ~ g without raising a syntax error.

No, you can't do that, not without radically altering how Python compiles bytecode. All expressions are first parsed into a Abstract Syntax Tree, then compiled into bytecode from that, and it is at the parsing stage that operands and operators are grouped.

By the time the bytecode runs you can no longer decide to accept two operands.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM