简体   繁体   English

是否有可能在Python中使用二进制运算符覆盖一元运算符?

[英]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. 我们可以用二进制运算符替换波形符运算符,这样我们就可以执行类似f ~ g的操作而不会引发语法错误。

No, you can't do that, not without radically altering how Python compiles bytecode. 不,你不能这样做,不能从根本上改变Python编译字节码的方式。 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. 到字节码运行时,您不能再决定接受两个操作数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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