简体   繁体   English

使用Python进行后期处理的优雅方式

[英]Elegant way of doing post-processing using Python

Considering the following example of post-processing using inheritance in python (from this website ): 考虑以下在python中使用继承的后处理示例(来自此网站 ):

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

Basically, when we are post-processing, we don't really care about the original invocation, we just want to work with the data returned by the function. 基本上,当我们进行后处理时,我们实际上并不关心原始调用,我们只想处理函数返回的数据。

So ideally, in my opinion, there should be no need for us to have redeclare the original function signature, just to be able to forward it to the original function. 因此,在我看来,理想情况下,我们无需重新声明原始函数签名,而只是能够将其转发到原始函数。

If FileCat class had 100 different functions ( cat1 , cat2 , cat3 ,...) that returned the same type of data and we wanted to use a post-processed NoEmpty version, then we would have to define the same 100 functions signatures in FileCatNoEmpty just to forward the calls. 如果FileCat类具有100个返回相同类型数据的不同函数( cat1cat2cat3等),而我们想使用后处理的NoEmpty版本,则必须在FileCatNoEmpty定义相同的100个函数签名只是转接电话。

So the question is: Is there a more elegant way of solving this problem? 所以问题是:是否有更优雅的方法来解决此问题?

That is, something like the FileCatNoEmpty class that would automatically make available all methods from FileCat but that still allows us to process the returned value? 也就是说,类似于FileCatNoEmpty类的东西可以自动使FileCat所有方法可用,但仍然允许我们处理返回的值吗?

Something like 就像是

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

Or maybe even another solution that does not uses inheritance. 也许甚至还有一个不使用继承的解决方案。

Thanks! 谢谢!

This answer, using a wrapper class that receives the original one in the constructor (instead of inheriting from it), solves the problem: 这个答案使用一个包装器类,该包装器类在构造函数中接收原始类(而不是从其继承),从而解决了以下问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM