请参见下面使用io.BufferedReader的Minimal python示例,该示例的行为非常奇怪。
3个调用之间的结果不一致。 2工作,最后一项,最重要的没有。我已经看了太久了,但没有发现问题。也许我做错了什么我想念。请看一下。我在Ubuntu 18.04.3 LTS上使用Python 2.7.15 +。
注意:结果在产生输出的行下面的###注释中。
from io import BytesIO, StringIO, BufferedReader, DEFAULT_BUFFER_SIZE
class MDReader(BufferedReader):
def __new__(cls, thingtoread, buffer_size=DEFAULT_BUFFER_SIZE):
iothing = BytesIO(thingtoread) \
if isinstance(thingtoread, str) \
else StringIO(thingtoread) \
if isinstance(thingtoread, unicode) \
else thingtoread
print iothing
return iothing and BufferedReader.__new__(cls, iothing, buffer_size)
text = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
mdr0 = BufferedReader.__new__(MDReader, BytesIO(text), DEFAULT_BUFFER_SIZE)
### <_io.BytesIO object at 0x7f348d06bbf0>
mdr1 = MDReader(BytesIO(text), DEFAULT_BUFFER_SIZE)
### <_io.BytesIO object at 0x7f348d06ba70>
mdr2 = MDReader(text, DEFAULT_BUFFER_SIZE)
### Traceback (most recent call last):
### File "<stdin>", line 1, in <module>
### File "./foo.py", line 19, in <module>
### mdr2 = MDReader(text, DEFAULT_BUFFER_SIZE)
### AttributeError: 'str' object has no attribute 'readable'
如果将new中的退货替换为:
self = iothing and BufferedReader.__new__(cls, iothing, buffer_size)
cls.__init__(self, iothing, buffer_size)
return self
def init(自身,* args,** kwargs):打印'init',args打印'init',kwargs
然后它的行为正确。除了忘记处理init。
,与任何事情都没有关系。很抱歉,发布了此内容。我想我只是看不到明显的东西,因为我在寻找具有价值的东西。卫生署!