Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

operator overloading - Turn `1+1==3` to return True on Python

Strange question: I want this expression to be True. 1+1==3, although I know it’s not :).

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

I know I can do it by creating a class (let’s say a) and overloading its __add__ function, but it requires me to write a(1)+a(1)==3.

Can I do it without writing an additional code (sure I can write code before and after, but the line above will be as is)?

question from:https://stackoverflow.com/questions/65865104/turn-11-3-to-return-true-on-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I managed to do it according to @ddulaney suggestion: create my own codec my_true and write my own decode function.

I have 3 files:

  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

Now run python3 run.py

Output is This is True...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...