如您所知,Python 支持字符串格式化,但我想谈谈它是如何在 Python 2 中实现的。如果我们键入a=u'абв'; b='abc'; c='%s%s'
,那么c
变量将具有 unicode 类型,因此格式化返回 unicode 对象。我是否有可能拥有自己的类myobject
,其中变量c
将具有myobject
类型?换句话说,我可以重载这个运算符吗?答案必须适用于 Python 3 和 Python 2,但用 Python 2 来描述我想要的东西更简单。谢谢!
class ustream(object):
'''ustream class provides an easy access for basic operations with Unicode
streams. The main advantage of this class is that it already has built-in
support for regular expressions and transliteration.'''
__slots__ = ['_stream_', 'array', 'stream']
def __init__(self, stream='', encoding=ENCODING['default']):
'''ustream.__init__([stream[, encoding]]) -> ustream'''
if isinstance(encoding, bstream):
encoding = encoding.stream
elif isinstance(encoding, ustream):
encoding = encoding.stream
if isinstance(stream, bytes):
stream = stream.decode(encoding)
elif isinstance(stream, string):
stream = string(stream)
elif isinstance(stream, bstream):
stream = stream.stream.decode(encoding)
elif isinstance(stream, ustream):
stream = stream.stream
else: # if unknown type
typename = type(stream).__name__
raise(TypeError('stream must be bytes or string, not %s' % typename))
self._stream_ = stream
@property
def array(self):
'''unicode stream as array'''
return([ord(char) for char in self.stream])
@property
def stream(self):
'''unicode stream as string'''
return(self._stream_)
def __mod__(self, stream):
'''ustream.__mod__(stream) <==> ustream % stream'''
result = self.stream % ustream(stream).stream
result = ustream(result)
return(result)
def __rmod__(self, stream):
'''ustream.__rmod__(stream) <==> stream % ustream'''
stream = ustream(stream)
stream = stream.stream
result = stream % self.stream
result = ustream(result)
return(result)
这是我笔记本电脑的代码示例。string
==str
适用于 Python 3 和unicode
Python 2。只是向后兼容。
这是我想要得到的。
>>> src = ustream('a stream')
>>> add = 'Hello man'
>>> result = '%s! Look here: we have %s!' % (add, src)
>>> type(result)
utstream
>>> print(result)
Hello man! Look here: we have a stream!