我用Python编写了以下代码,在一个参数“x”中包含多个函数:
stemming(removeStopWords(stringToList(removeRepChar(charOk(x)))))
我想知道我是否可以做一些事情来提高代码的可读性(如果它还不够可读的话)。我是否可以像在其他编程语言中那样省略这些括号?例如,在Haskell中:
stemming $ removeStopWords $ stringToList $ removeRepChar $ charOk x
还是一种无点的方法
funct = stemming.removeStopWords.stringToList.removeRepChar.charOk
funct(x)
我关心的是这样一种情况:我有数百个括号和函数,就像那些可能会变成更大的代码的括号和函数:
function1(function2(function3( ... (function300(x)) ... )))
我知道Python不是一种纯粹的函数式语言,但人们永远不会知道
这里有几个选项你可以试试。一种是编写自己的“apply”,它接受函数和参数
另一种方法是将函数放入类中并使用方法链接。您已经有了返回值的函数,只需返回
self
就我个人而言,我只是使用带括号的“原生”Python方式,但在answer by tdelaney上有一个稍微不同的说法,一个} 来提供^{} 范围中定义的任何函数
Chain
类使用^{或者使用
partial
和reduce
创建一个compose
函数(尽管我觉得这样的函数应该已经存在):相关问题 更多 >
编程相关推荐