繁体   English   中英

如何在 function 中定义 function?

[英]How to change a variable inside a function scope after defining the function in Python?

在定义 function 之后,我正在寻找一种方法来更改 function 中定义的变量。

例如

def GetNthPower(x) :
    n = None
    return x**n

my_numbers_list = [11,23,45,56,78,98]

# now if I feel like I need the 4th power of some numbers in the list 

GetNthPower.n = 4

for x in my_numbers_list :
    print GetNthPower(x)

#  If I want 7th power then
GetNthPower.n = 7 

这显然行不通,有没有办法做到这一点?

注意:我知道我们可以通过将“n”设置为 function 的参数来实现这一点,但出于特定原因我想这样做。 我希望我的 function 只有一个参数(用于在multiprocessing.Pool.map()中使用 function )。

您可以在函数内部定义 static 变量,就像您所做的一样:

def GetNthPower(x) :
    return x ** GetNthPower.n

GetNthPower.n = 3

print(GetNthPower(2)) #8

不过,请确保在首次使用之前正确初始化您的GetNthPower.n

如果你担心初始化,你可以 go 这个版本使用默认值1

def GetNthPower(x) :
    return x ** (GetNthPower.n if hasattr(GetNthPower, "n") else 1)

我认为编写一个需要两个 arguments 的 function 或使用预定义的**运算符仍然会更好。

不要使用一个 function; 使用闭包创建一个 function,使您的 function。

def nth_power_maker(n):
    def _(x):
        return x ** n
    return _

my_numbers_list = [11,23,45,56,78,98]

# now if I feel like I need the 4th power of some numbers in the list 

get_4th_power = nth_power_maker(4)

for x in my_numbers_list:
    print(get_4th_power(x))

get_7th_power = nth_power_maker(7)

或者,您可以使用functools.partial将关键字参数绑定到 function

from functools import partial

def get_nth_power(x, n):
    return x ** n

get_third = partial(get_nth_power, n=3)

get_third(4)
64

x = 4

# in a loop
for pow in [2, 4, 6, 8]:
    f = partial(get_nth_power, n=pow)
    f(x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM