繁体   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