[英]Minimal python example using BufferedReader acting strangely
請參閱下面使用 io.BufferedReader 的最小 python 示例,它的行為非常奇怪。
3 次調用之間的結果不一致。 2個工作,最后一個,最重要的一個沒有。 我一直在看這個太久,我沒有看到問題。 也許我做錯了什么我錯過了。 請看一下。 我在 Ubuntu 18.04.3 LTS 上使用 Python 2.7.15+。
注意:結果在產生 output 的行下方的 ### 注釋中。
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__(self, *args, **kwargs):
print '__init__', args
print '__init__', kwargs
然后它的行為正確。 除了我忘記處理 __init__ 之外,與其他任何事情都無關。 或者更好的方法是將參數處理代碼移動到 __init__ 並刪除 __new__。
很抱歉發布這個。 我想我只是沒有看到明顯的東西,因為我正在尋找具有價值的東西。 嗬!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.