Unicodeの問題を処理しているときに、私はそれを見つけ、unicode(self)
異なるself.__unicode__()
動作をします。
#-*- coding:utf-8 -*-
import sys
import dis
class test():
def __unicode__(self):
s = u'中文'
return s.encode('utf-8')
def __str__(self):
return self.__unicode__()
print dis.dis(test)
a = test()
print a
上記のコードは問題なく動作しますが、に変更self.__unicode__()
するunicode(self)
とエラーが表示されます。
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
問題のあるコードは次のとおりです。
#-*- coding:utf-8 -*-
import sys
import dis
class test():
def __unicode__(self):
s = u'中文'
return s.encode('utf-8')
def __str__(self):
return unicode(self)
print dis.dis(test)
a = test()
print a
Pythonがこれをどのように処理するかについて非常に興味があり、disモジュールを試しましたが、あまり多くの違いは見られませんでした。
Disassembly of __str__:
12 0 LOAD_FAST 0 (self)
3 LOAD_ATTR 0 (__unicode__)
6 CALL_FUNCTION 0
9 RETURN_VALUE
VS
Disassembly of __str__:
10 0 LOAD_GLOBAL 0 (unicode)
3 LOAD_FAST 0 (self)
6 CALL_FUNCTION 1
9 RETURN_VALUE