簡體   English   中英

Python:修改 function 中的封閉變量

[英]Python: modifying enclosing variable in function

有什么方法可以使用在主 function 之外編寫的函數來修改封閉變量?

我想做這個:

def modify_a():
    nonlocal a
    a =+ 1

def process_abc(some_criteria):
    a, b, c = generate(some_criteria)
    modify_a()
    return a, b, c

a, b, c = process_abc()

我嘗試了以下方法,但我想知道是否有辦法使上述工作。 如果有的話,這是不好的編碼習慣嗎?

def modify_a(a=a):
    a =+ 1

def process_abc(some_criteria):
    a, b, c = generate(some_criteria)
    a = modify_a(a)
    return a, b, c

a, b, c = process_abc()

唯一的方法是修改父框架。

無論哪種方式,這都是一個非常糟糕的主意。 函數是一種封裝形式。

如果你想修改父數據,你可以像這樣傳遞一個可變結構:

def modify_a(a=a):
    a[0] =+ 1

def process_abc(some_criteria):
    a, b, c = generate(some_criteria)
    a= [a]
    a = modify_a(a)[0]
    return a, b, c

a, b, c = process_abc()

不過,它通常不受歡迎。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM