高阶python函数并正确设置其属性

时间:2015-02-10 19:25:41

标签: python higher-order-functions

我目前正在编写一个函数,该函数生成并返回一个新函数来创建多项式表达式。我希望函数以串的形式存储多项式的系数和多项式本身。但是,如果没有解释器坚持新创建的函数没有这样的属性,我似乎无法设置任何一个属性。

请参阅下面的功能

def poly(coefs):
"""Return a function that represents the polynomial with these coefficients.
For example, if coefs=(10, 20, 30), return the function of x that computes
'30 * x**2 + 20 * x + 10'.  Also store the coefs on the .coefs attribute of
the function, and the str of the formula on the .__name__ attribute.'"""
# your code here (I won't repeat "your code here"; there's one for each function)
  def createPoly(x):
    formulaParts = []
    power = 0
    createPoly.coefs = coefs
    for coef in coefs:
      if power == 0:
        formulaParts += [('%d') % (coef)]
      elif power == 1:
        formulaParts += [('%d * x') % (coef)]
      else:
        formulaParts += [('%d * x**%d') % (coef, power)]
      power +=1
    createPoly.__name__ = ' + '.join(formulaParts[::-1])
    createPoly.value = eval(createPoly.__name__)
    return createPoly.value

  return createPoly

正如您所看到的,当我在上面的代码中设置属性并使用它们时,没有问题。但是,如果我在发生错误时使用下面的代码

y = poly((5,10,5))
print(y.__name__)

这可能是一件非常简单的事我忽略了。请帮忙

1 个答案:

答案 0 :(得分:2)

设置内部函数的代码不能在内部函数中:

def poly(coefs):
    def createPoly(x):
        createPoly.value = eval(createPoly.__name__)
        return createPoly.value

    formulaParts = []

    power = 0

    for coef in coefs:
        if power == 0:
            formulaParts += [('%d') % (coef)]
        elif power == 1:
            formulaParts += [('%d * x') % (coef)]
        else:
            formulaParts += [('%d * x**%d') % (coef, power)]
        power += 1
    createPoly.__name__ = ' + '.join(formulaParts[::-1])
    createPoly.coefs = coefs
    return createPoly