2015-02-10 43 views
0

我目前正在編寫一個函數來創建和返回一個新函數來創建多項式表達式。我想要函數以字符串形式存儲多項式和多項式的係數。但是,如果沒有解釋者堅持新創建的函數沒有這樣的屬性,我似乎沒有設置任何屬性。高階python函數並正確設置它們的屬性

請參考下面

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

這可能是很簡單的東西,我可以俯瞰下面那。請幫助

回答

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 
+0

輝煌。謝謝! – 2015-02-10 19:47:18