簡體   English   中英

如何使用 name 屬性實例化 io.TextIOWrapper 對象?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM