【发布时间】:2013-03-19 05:39:15
【问题描述】:
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(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__'
想法?
【问题讨论】:
-
你的代码真的像第一个例子那样缩进吗?
-
我不得不猜测你的问题是什么。如果我弄错了,请务必更新您的帖子以包含一个实际、明确的问题。
-
虽然这是一个很好的陷阱,但我想问一下为什么在 h*** 中你想继承 str 或 unicode?我的意思是,数据将是不可变的,因此生成的对象将毫无用处。
-
我在 [Edited...] 之后添加了更多内容。感觉很恶心,但我认为它没有打破任何 Pythonic 的期望。 repr 是一个字符串表示形式,如果需要,可以用来构建一个 unicode 对象,对吧?
-
@Kay:一点用处都没有。我已经使用它为 3D 图形软件包创建名称约定对象模型。基本上使名称成为一种特殊类型的字符串,它封装了使用约定的实用程序,但仍然可以透明地传递给本机 API。 3D 应用程序主要是 unicode,所以我试图保持一致。但是,在这个线程的情况下,我包装了一个 API 对象,我希望我的类的返回值是动态的,所以它只模仿一个真正的字符串 - 只需要传递 isinstance(instance, basestring)...don不要问...
标签: python class unicode subclass derived-class