有没有办法在Python中强制条件成立?我以前看过它是在Haskell中完成的,我想知道你是否可以用Python做.例如:
>>> 2+2==5
True
Run Code Online (Sandbox Code Playgroud)
您可以为子类int重新定义相等运算符:
>>> class MyInt(int):
... def __eq__(self, other):
... return True
...
>>> five = MyInt(5)
>>> five
5
>>> 2+2 == five
True
Run Code Online (Sandbox Code Playgroud)
这是尝试自己的这些答案中最不害的.但是,如果您在生产代码中执行此操作(或其中任何一项),您可能会被解雇.
那么你只需要设置四等于五.
import ctypes
def deref(addr, typ):
return ctypes.cast(addr, ctypes.POINTER(typ))
deref(id(4), ctypes.c_int)[6] = 5
2 + 2
#>>> 5
2 + 2 == 5
#>>> True
Run Code Online (Sandbox Code Playgroud)
明显...