【发布时间】:2013-10-04 20:16:37
【问题描述】:
我有一段简单的代码试图在 Python 中为file 提供便利。
class File:
def __init__(this, *args):
this._file = file(*args)
def __del__(this):
this._file.close()
def createCallForwarder(method):
return lambda obj,*args: method(obj._file, *args)
_dict = file.__dict__
for (k,v) in zip(_dict.keys(), _dict.values()):
if not (k.startswith('__') and k.endswith('__')):
if v.__class__.__name__ == 'method_descriptor':
File.__dict__[k] = createCallForwarder(v)
# get the repr method
File.__repr__ = createCallForwarder(dict_proxy['__repr__'])
如果我将File 更改为从object 继承,它不会让我分配方法。
为什么不一样?
【问题讨论】:
-
天哪,你想用你的代码实现什么?为什么不使用
file的子类,或者使用__getattr__挂钩来代理方法? -
如果您想在新样式类中做同样的事情,请使用
setattr:setattr(File, k, createCallForwarder(v)) -
谢谢!这正是我所需要的。我对 Python 没有太多经验。我只是想获得一个自行关闭的 File 对象,所以我不必关心。我不想泄露文件对象。
-
只是一个风格提示:按照惯例,Python 使用
self而不是this。 -
@AadityaKalsi:Python 文件对象已经这样做了。他们拥有自己的
__del__处理程序。
标签: python inheritance