Python print は を使用していないか__repr__
、印刷時にユニコード サブクラスを使用していません。私が間違っていることについての手がかりはありますか?__unicode__
__str__
これが私のコードです:
Python 2.5.2 の使用 (r252:60911、2009 年 10 月 13 日、14:11:59)
>>> class MyUni(unicode):
... def __repr__(self):
... return "__repr__"
... def __unicode__(self):
... return unicode("__unicode__")
... def __str__(self):
... return str("__str__")
...
>>> s = MyUni("HI")
>>> s
'__repr__'
>>> print s
'HI'
これが上記の正確な近似値であるかどうかはわかりませんが、比較のために:
>>> class MyUni(object):
... def __new__(cls, s):
... return super(MyUni, cls).__new__(cls)
... def __repr__(self):
... return "__repr__"
... def __unicode__(self):
... return unicode("__unicode__")
... def __str__(self):
... return str("__str__")
...
>>> s = MyUni("HI")
>>> s
'__repr__'
>>> print s
'__str__'
[編集済み...] isinstance(instance, basestring) であり、Unicode の戻り値を制御できる文字列オブジェクトを取得する最良の方法のように思えます。Unicode repr を使用すると...
>>> class UserUnicode(str):
... def __repr__(self):
... return "u'%s'" % super(UserUnicode, self).__str__()
... def __str__(self):
... return super(UserUnicode, self).__str__()
... def __unicode__(self):
... return unicode(super(UserUnicode, self).__str__())
...
>>> s = UserUnicode("HI")
>>> s
u'HI'
>>> print s
'HI'
>>> len(s)
2
上記の_ str _と_ repr _はこの例に何も追加していませんが、アイデアはパターンを明示的に示し、必要に応じて拡張することです。
このパターンが制御を許可することを証明するためだけに:
>>> class UserUnicode(str):
... def __repr__(self):
... return "u'%s'" % "__repr__"
... def __str__(self):
... return "__str__"
... def __unicode__(self):
... return unicode("__unicode__")
...
>>> s = UserUnicode("HI")
>>> s
u'__repr__'
>>> print s
'__str__'
考え?