2 回答

TA貢獻1776條經(jīng)驗 獲得超12個贊
就個人而言,我只是使用帶括號的“本機”Python 方式,其中一個Chain
類用于__getattr__
提供范圍內(nèi)定義的任何函數(shù)globals
。
class Chain:
? ? def __init__(self, val):
? ? ? ? self.val = val
? ? def __getattr__(self, f):
? ? ? ? return lambda: Chain(globals()[f](self.val))
def upper(s):
? ? return s.upper()
def pad(s):
? ? return "abc" + s + "xyz"
? ??
def swap(s):
? ? return s.swapcase()
print(Chain("foo").upper().pad().swap().val)
# ABCfooXYZ
或者使用partialandreduce來創(chuàng)建一個compose函數(shù)(雖然我覺得這樣的東西應(yīng)該已經(jīng)存在了):
from functools import reduce, partial
def compose(*fs):
? ? return partial(reduce, lambda x, f: f(x), fs)
print(compose(upper, pad, swap)("foo"))

TA貢獻1719條經(jīng)驗 獲得超6個贊
您可以嘗試以下幾個選項。一種是編寫您自己的帶有函數(shù)和參數(shù)的“應(yīng)用”。
def apply_functions(functions, arg):
for fctn in functions:
arg = fctn(arg)
return arg
result = apply_functions((charOk, removeRepChar, stringToList,
removeStopWords), x)
另一種方法是將您的函數(shù)放入一個類中并使用方法鏈接。您已經(jīng)有返回值的函數(shù),只需 returnself即可。
class Foo:
def __init__(self, df):
self.df = df
def charOk(self):
# do the operation
return self
def removeRepChar(self):
# do the operation
return self
etc...
result = Foo(x).charOk().removeRepChar().stringToList().removeStopWords()
添加回答
舉報