【问题标题】:Elegant way of doing post-processing using Python使用 Python 进行后处理的优雅方式
【发布时间】: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

或者甚至可能是另一个不使用继承的解决方案。

谢谢!

【问题讨论】:

标签: python inheritance overriding


【解决方案1】:

这个答案,使用一个在构造函数中接收原始的包装类(而不是从它继承),解决了这个问题:

https://stackoverflow.com/a/4723921/3444175

【讨论】:

    猜你喜欢
    • 2015-04-10
    • 2021-11-10
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多