Sto usando la versione Python: 2.7.3.Come funzionano le funzioni magiche e coercizione/magica di Python?
In Python, usiamo i metodi magici __str__
e __unicode__
per definire il comportamento di str
e unicode
sulle nostre classi personalizzate:
>>> 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'
Il comportamento suggerisce che il valore restituito da __str__
e __unicode__
è costretto a uno str
o unicode
a seconda del metodo magico da eseguire.
Tuttavia, se facciamo questo:
>>> 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
Calling str.mro()
e unicode.mro()
dice che entrambi sono sottoclassi di basestring
. Tuttavia, __unicode__
consente anche il ritorno degli oggetti buffer
, che eredita direttamente da object
e non eredita da basestring
.
Quindi, la mia domanda è, cosa succede in realtà quando str
e unicode
si chiamano? Quali sono i requisiti del valore di ritorno su __str__
e __unicode__
per l'uso in str
e unicode
?
Potrebbe essere necessario cercare il codice sorgente per scoprire questo – Eric