有没有办法让Python的函数更具可读性?

2024-10-16 22:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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不是一种纯粹的函数式语言,但人们永远不会知道


Tags: 函数代码参数haskell事情编程语言括号省略
2条回答

这里有几个选项你可以试试。一种是编写自己的“apply”,它接受函数和参数

def apply_functions(functions, arg):
    for fctn in functions:
        arg = fctn(arg)
    return arg

result = apply_functions((charOk, removeRepChar, stringToList,
    removeStopWords), x)

另一种方法是将函数放入类中并使用方法链接。您已经有了返回值的函数,只需返回self

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()

就我个人而言,我只是使用带括号的“原生”Python方式,但在answer by tdelaney上有一个稍微不同的说法,一个Chain类使用^{}来提供^{}范围中定义的任何函数

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

或者使用partialreduce创建一个compose函数(尽管我觉得这样的函数应该已经存在):

from functools import reduce, partial

def compose(*fs):
    return partial(reduce, lambda x, f: f(x), fs)

print(compose(upper, pad, swap)("foo"))

相关问题 更多 >