简体   繁体   中英

Elegant way of doing post-processing using Python

Considering the following example of post-processing using inheritance in python (from 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

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.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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