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

5 投票
3 回答
708 浏览
提问于 2025-04-15 11:13

为什么在下面的例子中,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 个回答

2

我发布了一个解决这个问题的临时办法。你可以看看,也许会对你有帮助:http://blog.teltub.com/2009/10/workaround-solution-to-python-strrepr.html

附言:也请阅读我最初提到这个问题的帖子……问题在于一些意想不到的表现,可能会让你感到惊讶……

3

我对代码做了一些修改,让事情变得更清楚:

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 中被重新定义,所以返回了一个“意外”的值。

9

str(A()) 这个操作会调用 __str__ 方法,而这个方法又会调用 dict.__str__()

实际上,是 dict.__str__() 返回了 repr(A) 的值。

撰写回答