0

我很好奇如何更改“真”以显示“假”结果,甚至可能吗?

True.__repr__() = False
True.__str__() = False

只有那些原始的想法浮现在我的脑海

4

2 回答 2

1

如果您尝试设置__str__或设置__repr__不同的功能,则会引发错误。

示例代码:

def return_false():
    return False

True.__str__ = return_false

print(True.__str__())

这将引发错误

AttributeError: 'bool' object attribute '__str__' is read-only
于 2016-05-25T13:22:28.293 回答
0

在 Python 3.X 中?我不这么认为,你不能分配给关键字True__str__并且__repr__方法是只读的。但是,在 Python 2 中,您可以在给定的范围内执行此操作。

class FakeTrue(int):
    def __new__(cls):
        return super(FakeTrue, cls).__new__(cls, 1)

    def __str__(self):
        return 'False'

    def __repr__(self):
        return 'False'

True = FakeTrue()

print True # False
print type(True) # <class '__main__.FakeTrue'>

print 1 == 1 # True
print type(1 == 1) # <type 'bool'>

请注意,它int.__eq__仍然返回单例True并且没有被覆盖。

于 2016-05-25T13:51:31.660 回答