如何系统且透明地重写 Python 方法
我正在寻找一个“简单”的解决方案来系统地覆盖Python中的一些继承方法(=>2.6)。根据我之前的问题此处,我将提出一个解决方案:
def override(cls, o):
"""Override class method(s)."""
for t in o: # possible problem; nondeterministic order
for name in o[t]:
mtbo= getattr(cls, name).im_func
om= t(mtbo)
om.__name__= mtbo.__name__
om.__doc__= mtbo.__doc__
# What additional magic is needed here to act as 'genuine' method of super class?
setattr(cls, name, om)
if __name__== '__main__':
class B(object):
def f1(self, val):
"""Doc of B.f1"""; print '1: ', val
def f2(self, val):
"""Doc of B.f2"""; print '2: ', val
class A(B):
pass
def t(f, msg):
def g(self, *args, **kwargs):
print msg, ' entering'; result= f(self, *args, **kwargs)
return g
t1= lambda f: t(f, 't1'); t2= lambda f: t(f, 't2')
override(A, {t1: ['f1', 'f2'], t2: ['f2']})
def tst(c):
c.f1(1); print c.f1.__name__, c.f1.__doc__
c.f2(2); print c.f2.__name__, c.f2.__doc__
tst(B()), tst(A())
这似乎足以满足我(当前)的目的。不过,我希望能够尽可能透明地覆盖,因此我将保留超类方法名称和文档。现在我的具体问题是:我应该保留其他东西吗?您对此有何解决方案?
更新: 我认为现在这个问题具有更广泛的影响:我想我应该(最初)问如何以足够合理的Python方式装饰方法或函数。
I'm looking for a 'simple' solution to override systematically some inherited methods in Python (=>2.6). Based on my previous question here, I'll come up a solution:
def override(cls, o):
"""Override class method(s)."""
for t in o: # possible problem; nondeterministic order
for name in o[t]:
mtbo= getattr(cls, name).im_func
om= t(mtbo)
om.__name__= mtbo.__name__
om.__doc__= mtbo.__doc__
# What additional magic is needed here to act as 'genuine' method of super class?
setattr(cls, name, om)
if __name__== '__main__':
class B(object):
def f1(self, val):
"""Doc of B.f1"""; print '1: ', val
def f2(self, val):
"""Doc of B.f2"""; print '2: ', val
class A(B):
pass
def t(f, msg):
def g(self, *args, **kwargs):
print msg, ' entering'; result= f(self, *args, **kwargs)
return g
t1= lambda f: t(f, 't1'); t2= lambda f: t(f, 't2')
override(A, {t1: ['f1', 'f2'], t2: ['f2']})
def tst(c):
c.f1(1); print c.f1.__name__, c.f1.__doc__
c.f2(2); print c.f2.__name__, c.f2.__doc__
tst(B()), tst(A())
This seems to work well enough for my (current) purposes. However I like to be able to override as transparent as possible, therefore I'll preserve the super class methods name and doc. Now my specific question is: should I preserve anything else? What is your solution for this?
Update:
I think now this questions has much wider ramifications: I quess I should have asked (originally) how to decorate methods, or functions reasonable enough pythonic way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以只调用 functools.update_wrapper 来确保复制相关属性,而不是手动分配 __name__ 、 __doc__ 以及其他可能的值。
Instead of manually assigning
__name__
,__doc__
, and possibly others, you can likely just callfunctools.update_wrapper
to ensure the relevant attributes are copied.