【发布时间】:2017-10-17 09:02:26
【问题描述】:
考虑以下在python中使用继承进行后处理的示例(来自this website):
import os
class FileCat(object):
def cat(self, filepath):
f = file(filepath)
lines = f.readlines()
f.close()
return lines
class FileCatNoEmpty(FileCat):
def cat(self, filepath):
lines = super(FileCatNoEmpty, self).cat(filepath)
nonempty_lines = [l for l in lines if l != '\n']
return nonempty_lines
基本上,当我们进行后处理时,我们并不真正关心原始调用,我们只想处理函数返回的数据。
因此,在我看来,理想情况下,我们不需要重新声明原始函数签名,只需将其转发给原始函数即可。
如果 FileCat 类有 100 个不同的函数(cat1,cat2,cat3,...)返回相同类型的数据,我们想使用后处理的 NoEmpty 版本,那么我们就必须在FileCatNoEmpty 中定义相同的 100 个函数签名来转发调用。
所以问题是:有没有更优雅的方法来解决这个问题?
也就是说,类似于FileCatNoEmpty 类的东西会自动使来自FileCat 的所有方法可用,但仍然允许我们处理返回的值?
有点像
class FileCatNoEmpty(FileCat):
# Any method with whatever arguments
def f(self,args):
lines = super(FileCatNoEmpty, self).f(args)
nonempty_lines = [l for l in lines if l != '\n']
return nonempty_lines
或者甚至可能是另一个不使用继承的解决方案。
谢谢!
【问题讨论】:
-
元类和 \from functools import wraps` 可能是你所追求的。这里有答案stackoverflow.com/a/11350487/3527520
标签: python inheritance overriding