Pourquoi str(A())
semble-t-il appeler A.__repr__()
et non dict.__str__()
dans l'exemple ci-dessous?Appel de méthode de classe de base Python: comportement inattendu
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
Sortie:
call: repr(A) expect: repr(A) get: repr(A)
call: str(A) expect: {} get: repr(A)
call: str(B) expect: {} get: {}
http://www.python.org/dev/peps/pep-3140/ – bernie