Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

scope - Python overwriting variables in nested functions

Suppose I have the following python code:

def outer():
    string = ""
    def inner():
        string = "String was changed by a nested function!"
    inner()
    return string

I want a call to outer() to return "String was changed by a nested function!", but I get "". I conclude that Python thinks that the line string = "string was changed by a nested function!" is a declaration of a new variable local to inner(). My question is: how do I tell Python that it should use the outer() string? I can't use the global keyword, because the string isn't global, it just lives in an outer scope. Ideas?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Python 3.x, you can use the nonlocal keyword:

def outer():
    string = ""
    def inner():
        nonlocal string
        string = "String was changed by a nested function!"
    inner()
    return string

In Python 2.x, you could use a list with a single element and overwrite that single element:

def outer():
    string = [""]
    def inner():
        string[0] = "String was changed by a nested function!"
    inner()
    return string[0]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...