【问题标题】:Turn `1+1==3` to return True on Python转 `1+1==3`​​ 在 Python 上返回 True
【发布时间】:2021-01-23 22:25:50
【问题描述】:

奇怪的问题:我希望这个表达式为真。 1+1==3,虽然我知道不是:)。

if 1+1==3: 
    print("This is True...")

我知道我可以通过创建一个类(比如说a)并重载它的__add__ 函数来做到这一点,但这需要我写a(1)+a(1)==3

我可以不写额外的代码来做吗(确定我可以在之前和之后写代码,但上面的行会保持原样)?

【问题讨论】:

  • 您可以注册一个新的源编解码器,将文字包装在具有必要覆盖的自定义类中。 This answer 有一些编写自定义源编解码器的指针。
  • 看看这个answer。看起来你不能在“普通”Python 上做到这一点
  • @ddulaney 好主意,我会检查..

标签: python operator-overloading


【解决方案1】:

我按照@ddulaney 的建议设法做到了:创建我自己的编解码器my_true 并编写我自己的decode 函数。

我有 3 个文件:

  1. register.py
import codecs, io, encodings
from encodings import utf_8

def my_true_decode(input, errors="strict"):
    raw = bytes(input).decode("utf-8")
    code = raw.replace('1+1==3','1+1==2')
    return code, len(input)

def search_function(encoding):
    if encoding != "my_true":
        return None
    utf8 = encodings.search_function("utf8")
    return codecs.CodecInfo(
        name="my_true",
        encode=utf8.encode,
        decode=my_true_decode,
    )

codecs.register(search_function)
  1. script.py
# coding: my_true
if 1+1==3: 
    print("This is True...")
  1. run.py
import register
import script

现在运行python3 run.py

输出为This is True...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-16
    • 2019-01-09
    • 2012-09-05
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    相关资源
    最近更新 更多