簡體   English   中英

使用Python進行后期處理的優雅方式

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

考慮以下在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

基本上,當我們進行后處理時,我們實際上並不關心原始調用,我們只想處理函數返回的數據。

因此,在我看來,理想情況下,我們無需重新聲明原始函數簽名,而只是能夠將其轉發到原始函數。

如果FileCat類具有100個返回相同類型數據的不同函數( cat1cat2cat3等),而我們想使用后處理的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

也許甚至還有一個不使用繼承的解決方案。

謝謝!

這個答案使用一個包裝器類,該包裝器類在構造函數中接收原始類(而不是從其繼承),從而解決了以下問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM