【发布时间】:2012-09-19 22:02:47
【问题描述】:
在尝试计算另一个 question 时,我感到有点意外。
这对我来说似乎非常奇怪,我认为值得提出这个问题。为什么__getattr__ 似乎不能与with 一起使用?
如果我制作这个对象:
class FileHolder(object):
def __init__(self,*args,**kwargs):
self.f= file(*args,**kwargs)
def __getattr__(self,item):
return getattr(self.f,item)
并与with一起使用,
>>> a= FileHolder("a","w")
>>> a.write
<built-in method write of file object at 0x018D75F8>
>>> with a as f:
... print f
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __exit__
>>> a.__exit__
<built-in method __exit__ of file object at 0x018D75F8>
为什么会这样?
编辑
>>> object.__exit__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'object' has no attribute '__exit__'
绝对不是继承__exit__
【问题讨论】:
-
这里发生了一些事情,在您的类定义中,您将
FileHolder设为object的子类。但是在你下面的代码中,它说a是一个file对象。那是不一致的。 -
@jedwards 老实说不是。自己测试一下:)
-
@jedwards,
__exit__来自分配给self.f的file对象,如果你问type(a),你会得到FileHolder。 -
@Adam,你说得对——实际上我并没有创建这个类(我做了类似
class FileHolder(object): pass之类的事情)——对我有用。
标签: python attr with-statement