![](/img/trans.png)
[英]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.