別の質問を解決しようとしているときに、これに少し驚きました。
これは私には非常に奇妙に思えたので、質問する価値があると思いました。で動作しない__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__