Big*_*her 4 python operator-overloading unary-operator
我试图定义一个类并覆盖代字号运算符:
class foo:
def __invert__(self, other)
return 1232 # a random number , just as test
Run Code Online (Sandbox Code Playgroud)
然后称之为:
>>> f = foo()
>>> g = foo()
>>> f ~ g
File "<input>", line 1
f ~ g
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
我们可以用二进制运算符替换波浪运算符,这样我们就可以像f ~ g不引发语法错误那样进行操作.
Mar*_*ers 11
不,你不能这样做,不能从根本上改变Python编译字节码的方式.所有表达式首先被解析为抽象语法树,然后从中编译成字节码,并且在解析阶段,操作数和运算符被分组.
到字节码运行时,您不能再决定接受两个操作数.