2009-04-23 14 views
5

str(A())は以下の例ではdict.__str__()ではなくA.__repr__()と表示されるのはなぜですか?Python基本クラスのメソッド呼び出し:予期しない動作

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 

出力:

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

答えて

9

str(A())dict.__str__()を呼び出す順番に、__str__を呼び出して行います。

dict.__str__()は、値repr(A)を返します。

3
私は物事をクリアするためにコードを変更した

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) 

、出力は次のとおりです。

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

は、STR機能が自動的にはrepr関数を呼び出すことを意味します。そしてクラスAで再定義されたので、 '予期しない'値を返します。

関連する問題