【问题标题】:Is it possible to change __repr__ of True to be False?是否可以将 True 的 __repr__ 更改为 False?
【发布时间】:2016-09-23 03:09:06
【问题描述】:

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

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

我脑子里只有那些原始的想法

【问题讨论】:

  • 你有最终目的吗?
  • 你不能改变内置类型的dunder方法,但是你可以创建一个子类并覆盖__repr__那里。
  • 您为什么要这样做?只是为了让事情变得更复杂?
  • 也许是禁果?
  • 我在做运动,想偷偷摸摸,反正谢谢解答

标签: python python-3.x repr


【解决方案1】:

如果您尝试将__str____repr__ 设置为不同的函数,则会引发错误。

示例代码:

def return_false():
    return False

True.__str__ = return_false

print(True.__str__())

这会报错

AttributeError: 'bool' object attribute '__str__' is read-only

【讨论】:

    【解决方案2】:

    在 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 并且未被覆盖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2017-11-05
      • 2013-09-09
      • 2017-07-02
      • 2021-11-08
      • 1970-01-01
      相关资源
      最近更新 更多