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

ste*_*han 5 python inheritance dictionary

为什么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
Run Code Online (Sandbox Code Playgroud)

输出:

call: repr(A)  expect: repr(A)  get: repr(A)
call: str(A)   expect: {}       get: repr(A)
call: str(B)   expect: {}       get: {}
Run Code Online (Sandbox Code Playgroud)

cod*_*ape 9

str(A())打电话__str__,然后打电话dict.__str__().

dict.__str__()返回值repr(A).