2009-04-23 18 views
5

¿Por qué str(A()) aparentemente llama A.__repr__() y no dict.__str__() en el ejemplo siguiente?Llamada de método de clase base de Python: comportamiento inesperado

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 

Salida:

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

Respuesta

9

str(A())__str__ funciona la llamada, a su vez llamar dict.__str__().

Es dict.__str__() que devuelve el valor repr (A).

3

he modificado el código para aclarar las cosas:

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) 

Y la salida es:

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

Lo que significa que la función str llama a la función repr automáticamente. Y como se redefinió con la clase A, devuelve el valor "inesperado".

Cuestiones relacionadas