【问题标题】:Problem when using python xoltar toolkit, error raised when employ closure使用 python xoltar 工具包时出现问题,使用闭包时出现错误
【发布时间】:2011-10-01 21:08:41
【问题描述】:

最近我在阅读一些关于 Python 函数式编程的资料,其中之一在这里:http://www.ibm.com/developerworks/linux/library/l-prog2/index.html

我输入代码:

from functional import *

taxdue        = lambda: (income-deduct)*rate
incomeClosure = lambda income,taxdue: closure(taxdue)
deductClosure = lambda deduct,taxdue: closure(taxdue)
rateClosure   = lambda rate,taxdue: closure(taxdue)

taxFP = taxdue
taxFP = incomeClosure(50000,taxFP)
taxFP = rateClosure(0.30,taxFP)
taxFP = deductClosure(10000,taxFP)

print"Functional taxes due =",taxFP()

print"Lisp-style taxes due =", \
      incomeClosure(50000,
          rateClosure(0.30,
              deductClosure(10000, taxdue)))()

但最终得到以下错误信息:

Functional taxes due =
Traceback (most recent call last):
  File "E:/Study/python/FP/FP1.py", line 16, in <module>
    print"Functional taxes due =",taxFP()
  File "E:/Study/python/FP/FP1.py", line 5, in <lambda>
    taxdue =        lambda: (income-deduct)*rate
NameError: global name 'income' is not defined

我用的是python 2.7.1,想知道是什么问题,先谢谢了。

【问题讨论】:

  • lambda taxdue 加参数后仍有一些错误,直接或间接调用 taxdue 时要求参数,貌似闭包没有绑定数据到参数

标签: python functional-programming closures


【解决方案1】:

问题是变量incomedeductrate 在您执行lambda: (income-deduct)*rate 时并未在任何地方定义。

也许您打算将它们作为 lambda 的参数?

【讨论】:

  • 是的,但是还是有错误,直接或者间接调用taxdue的时候要参数,貌似闭包没有绑定数据到参数
猜你喜欢
  • 1970-01-01
  • 2022-10-23
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 2015-05-19
  • 2012-06-19
  • 2022-01-19
  • 1970-01-01
相关资源
最近更新 更多