Python 如何从外部使用变量编写函数?

Python 如何从外部使用变量编写函数?,python,function,scope,definition,Python,Function,Scope,Definition,我希望你能帮忙。我正在寻找一种方法来编写一个函数,在以后插入一项。让我给你举个例子: def general_poly(L): """ L, a list of numbers (n0, n1, n2, ... nk) Returns a function, which when applied to a value x, returns the value n0 * x^k + n1 * x^(k-1) + ... nk *

我希望你能帮忙。我正在寻找一种方法来编写一个函数,在以后插入一项。让我给你举个例子:

def general_poly(L):
        """ 
        L, a list of numbers (n0, n1, n2, ... nk)
        Returns a function, which when applied to a value x, returns the value 
        n0 * x^k + n1 * x^(k-1) + ... nk * x^0 
        """
        x = 1
        res = 0
        n = len(L)-1
        for e in range(len(L)):
            res += L[e]*x**n
            n -= 1
        return res

我想我可以在这里给
x
一个值,一旦我做了
general_poly(L)(10)
它就会被替换,这样
x=10
,但显然不是那么容易。我必须更改/添加什么才能使我的功能正常工作?函数如何知道乘法是
x
?谢谢你们的帮助,伙计们

要求您返回一个函数,但您返回的是计算值:

def general_poly(L):
    """ 
    L, a list of numbers (n0, n1, n2, ... nk)
    Returns a function, which when applied to a value x, returns the value 
    n0 * x^k + n1 * x^(k-1) + ... nk * x^0 
    """
    def inner(x):
        res = 0
        n = len(L)-1
        for e in range(len(L)):
            res += L[e]*x**n
            n -= 1
        return res
    return inner
现在,
general\u poly(L)(10)
将实现您期望的功能,但如果您将其指定给一个值,则它可能更有用,因此可以多次调用它,例如:

L = [...]
fn = general_poly(L)
print(fn(10))
print(fn(3))
您还可以将
内部
重写为:

def general_poly(L):
    return lambda x: sum(e*x**n for n, e in enumerate(reversed(L)))

如果
x
是全局的,您需要通过
global x
明确地告诉Python。它确实做了我想要的,谢谢。但是我仍然感到困惑:
internal
的返回基本上返回了设置,这样一旦
x
被给定,内部函数就可以被解决。对吗?如果是,general_poly(L)如何知道
x
在general_poly的def之后?因为inner被定义为inner(x)?是的,
general_poly
是一个参数(L)的函数,该参数返回一个带一个参数(x)的函数。显然,参数的实际名称无关紧要。
L
仍然可以被
internal()
访问的事实被称为闭包。为什么要将
internal
重写为lambda函数?因为函数现在只是一个单行程序,而且给函数命名没有实际价值,既然你刚刚还了它。这是风格的问题,我同意其他人有不同的观点。
def general_poly (L):
    """ L, a list of numbers (n0, n1, n2, ... nk)
    Returns a function, which when applied to a value x, returns the value 
    n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """

    def inner(x):
        L.reverse()
        return sum(e*x**L.index(e) for e in L)
    return inner