[英]Python - Attribute Error '_io.TextIOWrapper' object has no attribute 'open'
[英]How to instantiate an io.TextIOWrapper object with a name attribute?
import sys
print(sys.stdin)
print(type(sys.stdin))
print(sys.stdin.name)
print(sys.stdin.__dict__)
執行上述操作后,輸出如下:
<_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>
<class '_io.TextIOWrapper'>
<stdin>
{'mode': 'r'}
所以從上面的片段和輸出中,我可以看到name
是_io.TextIOWrapper
實例的一個屬性,代表sys.stdin
。 從io.TextIOWrapper
上的文檔(例如通過$ pydoc io.TextIOWrapper
) $ pydoc io.TextIOWrapper
,它確實將name
列為數據描述符。 但是,無論出於何種原因, name
都不會在其__dict__
顯示為項目。
當我手動創建一個io.TextIOWrapper
實例時,例如:
import io
a = io.TextIOWrapper(io.BytesIO())
print(a)
a.name
<_io.TextIOWrapper encoding='UTF-8'>
被打印出來。 但是a.name
行拋出錯誤: AttributeError: '_io.BytesIO' object has no attribute 'name'
; 我預期的AttributeError
,但我沒想到它會說它是一個_io.BytesIO
對象。
然后我嘗試創建一個子類並手動附加name
屬性,如下所示:
import io
class NamedTextIOWrapper(io.TextIOWrapper):
def __init__(self, buffer, name=None, **kwargs):
self.name = name
io.TextIOWrapper.__init__(self, buffer, **kwargs)
input = io.BytesIO('abc')
stdin = NamedTextIOWrapper(input, name='<stdin>', encoding='utf-8')
print(stdin.name)
但是,這會遇到: AttributeError: attribute 'name' of '_io.TextIOWrapper' objects is not writable
。
理想情況下,我還希望能夠在手動實例化的io.TextIOWrapper
對象中維護sys.stdin
實例中看似可用的mode
屬性。 而且對於sys.stdout
等效項,我認為除了name
應設置為'<stdout>'
並將mode
為'w'
外,我認為它們是相同'w'
。
您可以使用一個在請求name
屬性時返回對象屬性字典的name
鍵的方法來覆蓋__getattribute__
方法:
class NamedTextIOWrapper(io.TextIOWrapper):
def __init__(self, buffer, name=None, **kwargs):
vars(self)['name'] = name
super().__init__(buffer, **kwargs)
def __getattribute__(self, name):
if name == 'name':
return vars(self)['name']
return super().__getattribute__(name)
以便:
input = io.BytesIO(b'abc')
stdin = NamedTextIOWrapper(input, name='<stdin>', encoding='utf-8')
print(stdin.name)
輸出:
<stdin>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.