蟒紋不使用__repr__
,__unicode__
或__str__
我的Unicode的子類。任何線索,我做錯了什麼?Python打印不使用__repr__,__unicode__或__str__爲unicode子類?打印時
這裏是我的代碼:
使用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(例如,即basestring),並提供了統一重新控制轉值,並使用Unicode再版是...
>>> 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
的_ 海峽 _和_ 再版 _上面沒有加入到這個例子,但這個想法是明確的顯示模式,根據需要進行擴展。
只是爲了證明,這種模式賦予控制:
>>> 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__'
的思考?
你的代碼是否真的像第一個例子一樣縮進? – GreenMatt
我不得不猜測你的問題是什麼。如果我認爲它錯了,請更新您的帖子,*包括一個實際的,明確的問題*。 –
儘管這是一個很好的陷阱,但我想問一下,爲什麼在h ***中想要繼承str或unicode?我的意思是,數據將是不可變的,所以它產生的對象將是無用的。 – kay