代码之家  ›  专栏  ›  技术社区  ›  stephan

python基类方法调用:意外行为

  •  5
  • stephan  · 技术社区  · 15 年前

    为什么 str(A()) 貌似叫 A.__repr__() 而不是 dict.__str__() 在下面的例子中?

    class A(dict):
        def __repr__(self):
            return 'repr(A)'
        def __str__(self):
            return dict.__str__(self)
    
    class B(dict):
        def __str__(self):
            return dict.__str__(self)
    
    print 'call: repr(A)  expect: repr(A)  get:', repr(A())   # works
    print 'call: str(A)   expect: {}       get:', str(A())    # does not work
    print 'call: str(B)   expect: {}       get:', str(B())    # works
    

    输出:

    call: repr(A)  expect: repr(A)  get: repr(A)
    call: str(A)   expect: {}       get: repr(A)
    call: str(B)   expect: {}       get: {}
    
    3 回复  |  直到 12 年前
        1
  •  9
  •   codeape    15 年前

    str(A()) 是否调用 __str__ ,依次呼叫 dict.__str__() .

    它是 D.T.S. 返回值repr(a)。

        2
  •  3
  •   rpr    15 年前

    我已经修改了代码来清除:

    class A(dict):
       def __repr__(self):
          print "repr of A called",
          return 'repr(A)'
       def __str__(self):
          print "str of A called",
          return dict.__str__(self)
    
    class B(dict):
       def __str__(self):
          print "str of B called",
          return dict.__str__(self)
    

    输出为:

    >>> print 'call: repr(A)  expect: repr(A)  get:', repr(A())
    call: repr(A)  expect: repr(A)  get: repr of A called repr(A)
    >>> print 'call: str(A)   expect: {}       get:', str(A())
    call: str(A)   expect: {}       get: str of A called repr of A called repr(A)
    >>> print 'call: str(B)   expect: {}       get:', str(B())
    call: str(B)   expect: {}       get: str of B called {}
    

    这意味着str函数会自动调用repr函数。因为它是用类A重新定义的,所以它返回“unexpected”值。

        3
  •  2
  •   Ehsan Foroughi    15 年前

    我已经发布了一个解决方案。过来看。。。你可能会发现它很有用: http://blog.teltub.com/2009/10/workaround-solution-to-python-strrepr.html

    另外,请阅读我介绍这个问题的原始帖子……有一个问题是意想不到的行为让你吃惊…