2009-04-23 16 views
5

प्रतीत होता है A.__repr__() और dict.__str__() क्यों नीचे दिए गए उदाहरण में?पायथन बेस क्लास विधि कॉल: अप्रत्याशित व्यवहार

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 (ए) देता है।

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 समारोह रेपर समारोह स्वचालित रूप से कहता है कि। और चूंकि इसे कक्षा ए के साथ फिर से परिभाषित किया गया था, यह 'अप्रत्याशित' मान देता है।

2

मैंने इसके लिए एक समाधान समाधान पोस्ट किया है। इसे जांचें ... आपको यह उपयोगी लगेगा: http://blog.teltub.com/2009/10/workaround-solution-to-python-strrepr.html

पीएस मूल पोस्ट पढ़ें जहां मैंने इस मुद्दे को भी पेश किया था ... समस्या अनपेक्षित व्यवहार है जो आपको आश्चर्य से पकड़ती है ...

संबंधित मुद्दे