【问题标题】:Chaining functions with multiple arguments具有多个参数的链接函数
【发布时间】:2016-06-01 02:29:35
【问题描述】:

有没有办法用多个参数链接函数?

目前我在Python“链接”我的操作如下:

def createDirIfNecessary(directoryName):
    if not os.path.exists(directoryName):
        print 'Creating directory [%s]'% directoryName
        os.makedirs(directoryName)
    return directoryName

cakeName = 'lemonPie'
cookDate = '2011-01-04'

#yewww very ugly, big blob of function call ...
myDir = os.path.join(getDbDir('kitchenCupboardDir'),'cakes', cakeName)
file  = os.path.join(createDirIfNecessary(myDir), cookDate + '.gz')

例如,在R 中,有一种非常优雅的方式可以使用“管道”%>% 运算符(Haskell 中也存在管道运算符)。等效代码为:

cakeName = 'lemonPie'
cookDate = '2011-01-04'

file = getDbDir('kitchenCupboardDir') %>%
         file.path('cakes', cakeName) %>%
         createDirIfNecessary %>%
         file.path(paste0(cookDate,'.gz'))

这里只有 4 个函数,可以有 6、7 个函数,可以轻松链接。不幸的是我不能使用R,我想知道python 2.7中是否有解决方案

它与这个主题非常相关,但有更多的论点: Better way to call a chain of functions in python?

【问题讨论】:

    标签: python r python-2.7 functional-programming chain


    【解决方案1】:

    fn(see on GitHub 具有 >> 运算符,以及许多其他函数式编程的好东西。您可以在 python 中进行函数式编程,即使 (see also this answer) 这并不是真正的最佳方式。 Python 可以通过方法“链接”函数:

    file = getDbDir(...).makePath(...).createDir(...).getPath(...)
    

    这是一种连锁操作的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      相关资源
      最近更新 更多