Python强迫一个条件

Bet*_*cay 8 python

有没有办法在Python中强制条件成立?我以前看过它是在Haskell中完成的,我想知道你是否可以用Python做.例如:

>>> 2+2==5
True
Run Code Online (Sandbox Code Playgroud)

Aar*_*all 8

您可以为子类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)

这是尝试自己的这些答案中最不害的.但是,如果您在生产代码中执行此操作(或其中任何一项),您可能会被解雇.


Vee*_*rac 8

那么你只需要设置四等于五.

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)

明显...

  • 这是对你们大胆的挑战:将29设置为100(因为29不会使用太多,所以它不会使解释器崩溃)并尝试将其更改为*返回*.解决方案和其他更高级的尝试[可在此处获取](http://www.reddit.com/r/Python/comments/2441cv/can_you_change_the_value_of_1/). (2认同)