我很好奇如何更改“真”以显示“假”结果,甚至可能吗?
True.__repr__() = False
True.__str__() = False
只有那些原始的想法浮现在我的脑海
我很好奇如何更改“真”以显示“假”结果,甚至可能吗?
True.__repr__() = False
True.__str__() = False
只有那些原始的想法浮现在我的脑海
如果您尝试设置__str__
或设置__repr__
不同的功能,则会引发错误。
示例代码:
def return_false():
return False
True.__str__ = return_false
print(True.__str__())
这将引发错误
AttributeError: 'bool' object attribute '__str__' is read-only
在 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
并且没有被覆盖。