2009-04-23 8 views
5

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: {} 
+0

http://www.python.org/dev/peps/pep-3140/ – bernie

Répondre

9

str(A()) n'appelle __str__, à son tour appeler dict.__str__(). Il s'agit du dict.__str__() qui renvoie la valeur repr (A).

3

J'ai modifié le code pour effacer les choses:

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) 

Et la sortie est:

>>> 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 {} 

Ce qui signifie que la fonction str appelle automatiquement la fonction rééd. Et comme il a été redéfini avec la classe A, il renvoie la valeur "inattendue".

Questions connexes