मैं पायथन संस्करण का उपयोग कर रहा हूं: 2.7.3।पायथन की स्ट्रिंग और यूनिकोड जबरन/जादू कार्य कैसे काम करते हैं?
अजगर में, हम str
और unicode
हमारे कस्टम वर्गों पर के व्यवहार को परिभाषित करने के जादू तरीकों __str__
और __unicode__
का उपयोग करें:
>>> class A(object):
def __str__(self):
print 'Casting A to str'
return u'String'
def __unicode__(self):
print 'Casting A to unicode'
return 'Unicode'
>>> a = A()
>>> str(a)
Casting A to str
'String'
>>> unicode(a)
Casting A to unicode
u'Unicode'
व्यवहार चलता है कि __str__
और __unicode__
से रिटर्न मान पर मजबूर कर रहा है या तो str
या unicode
किस जादू विधि को चलाया जाता है इसके आधार पर।
हालांकि, अगर हम ऐसा करते हैं:
>>> class B(object):
def __str__(self):
print 'Casting B to str'
return A()
def __unicode__(self):
print 'Casting B to unicode'
return A()
>>> b = B()
>>> str(b)
Casting B to str
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
str(b)
TypeError: __str__ returned non-string (type A)
>>> unicode(b)
Casting B to unicode
Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
unicode(b)
TypeError: coercing to Unicode: need string or buffer, A found
str.mro()
और unicode.mro()
कॉलिंग का कहना है कि दोनों basestring
की उपवर्गों हैं। हालांकि, __unicode__
buffer
ऑब्जेक्ट्स को लौटने की भी अनुमति देता है, जो सीधे object
से प्राप्त होता है और basestring
से प्राप्त नहीं होता है।
तो, मेरा सवाल यह है कि वास्तव में क्या होता है जब str
और unicode
कहा जाता है? __str__
और __unicode__
पर str
और unicode
पर उपयोग के लिए वापसी मूल्य आवश्यकताएं क्या हैं?
आपको यह पता लगाने के लिए स्रोत कोड को देखने की आवश्यकता हो सकती है – Eric