【问题标题】:__repr__ vs repr__repr__ 与 repr
【发布时间】:2012-10-04 08:44:25
【问题描述】:

这两种方法有区别吗?

例如,

from datetime import date
today = date(2012, 10, 13)
repr(today)
'datetime.date(2012, 10, 13);

today.__repr__()
'datetime.date(2012, 10, 13)'

他们似乎做同样的事情,但为什么有人要使用后者而不是常规的 repr?

【问题讨论】:

    标签: python repr


    【解决方案1】:

    都是一样的

    认为repr() 包含以下代码:

    def repr(obj):
        return obj.__repr__()
    

    它所做的只是调用对象的__repr__() 函数。我不确定为什么有人需要显式调用对象的 __repr__() 方法。事实上,这样做通常是一种糟糕的编码风格(它会让人感到困惑,并导致程序员提出像你刚才所做的那样的问题)。

    【讨论】:

      【解决方案2】:

      __repr__ method 用于实现 repr() 的自定义结果。它由repr()str() 使用(如果未定义__str__)。你不应该明确地调用__repr__

      不同之处在于 repr() 强制将字符串作为返回类型,而 repr() 在类对象而非实例本身上查找 __repr__

      >>>> class C(object):
      ....   def __repr__(self):
      ....     return 1 # invalid non-string value
      ....
      >>>> c = C()
      >>>> c.__repr__() # works
      1
      >>>> repr(c) # enforces the rule
      Traceback (most recent call last):
        File "<console>", line 1, in <module>
      TypeError: __repr__ returned non-repr (type 'int')
      >>>> c # calls repr() implicitly
      Traceback (most recent call last):
        File "<console>", line 1, in <module>
      TypeError: __repr__ returned non-repr (type 'int')
      >>>> str(c)  # also uses __repr__
      Traceback (most recent call last):
        File "<console>", line 1, in <module>
      TypeError: __str__ returned non-str (type 'int')
      >>>> c.__repr__ = lambda: "a"
      >>>> c.__repr__() # lookup on instance
      'a'
      >>>> repr(c) # old method from the class
      Traceback (most recent call last):
        File "<console>", line 1, in <module>
      TypeError: __repr__ returned non-repr (type 'int')
      >>>>
      

      【讨论】:

        猜你喜欢
        • 2020-08-25
        • 2019-04-26
        • 2022-11-13
        • 2022-08-18
        • 2013-10-20
        • 2018-04-10
        • 2021-12-21
        • 2011-12-07
        • 1970-01-01
        相关资源
        最近更新 更多