![](/img/trans.png)
[英]python-pptx How to make legend show Series name rather than category name
[英]How to make python functions bind enclosing variable to value rather than to name
在python函數中,從封閉范圍引用變量是完全合法的。 這些變量引用函數調用時所具有的任何值。 因此,例如
x = 1 # unused
def foo(y):
return x+y
x=10
print(foo(1)) # prints 11
x=11
print(foo(1)) # prints 12
是否可以將變量x
凍結為創建時x
的值? 也就是說,我希望foo
的x
綁定到外部x
的值而不是其名稱。 基本上我想要的行為是
x = 1
def foo(y):
return 1+y # I'd rather not hard code the value of x here
x=10
print(foo(1)) # prints 2
x=11
print(foo(1)) # prints 2
我目前有一個可行的解決方案,但是它不是很可讀,我認為可能會有更好的解決方案(也許是裝飾器?)
我的解決方案
x = 1
def wrapper():
local_x = x
def foo(y):
return local_x+y
return foo
foo = wrapper()
x=10
print(foo(1)) # prints 2
x=11
print(foo(1)) # prints 2
您還可以利用默認參數:
x = 1
def foo(y, x=x):
return x + y
x=10
print(foo(1)) # prints 2
x=11
print(foo(1)) # prints 2
使用functools.partial來應用第一個參數,並獲得一個接受一個參數的新函數。 我選擇不裝飾add函數,因為它在其他地方非常通用且有用。
from functools import partial
from operator import add # does same thing as your foo
x = 1
foo = partial(add, x)
print(foo(1)) # prints 2
x = 11
print(foo(1)) # prints 2
為了與原始解決方案保持一致,您還可以執行類似的操作。
def wrapper(localx):
def foo(y):
return localx + y
return foo
foo2 = wrapper(x)
print(foo2(1)) # prints 12
請注意,現在已經減少了對全局變量的依賴,您甚至可以將文字值傳遞給wrapper
(例如foo3 = wrapper(5)
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.