2009-04-23 22 views
5

Dlaczego str(A()) na pozór nazywa się A.__repr__(), a nie dict.__str__() w poniższym przykładzie?Wywołanie metody klasy podstawowej Pythona: nieoczekiwane zachowanie

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 

wyjściowa:

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

Odpowiedz

9

str(A()) zwoła __str__ kolei nazywając dict.__str__().

To jest dict.__str__(), która zwraca wartość repr (A).

3

Mam zmodyfikowany kod, aby usunąć rzeczy:

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) 

a wyjście jest:

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

znaczy, że funkcja str wywołuje funkcję repr automatycznie. A ponieważ został przedefiniowany w klasie A, zwraca wartość "nieoczekiwaną".

Powiązane problemy