How to access the variable defined in outer method from innner method

Question:

I have a simple python code as follows:

def outer():
    x = None
    y = None
    z = None

    def set():
        x = 1
        y = "Y"
        z = 2

    def get():
        return x, y, z

    set()
    m, s, n = get()
    print("%s, %s, %s" % (m, s, n))


outer()

I would like to get 1 Y 2, but the result is None None None.

It looks that the variable x,y,z is not set by the set method,

I would ask how to get the result 1 Y 2

Asked By: Tom

||

Answers:

You can do it using the nonlocal keyword.

def outer():
    x = None
    y = None
    z = None

    def set():
        nonlocal x
        nonlocal y
        nonlocal z
        x = 1
        y = "Y"
        z = 2

    def get():
        return x, y, z

    set()
    m, s, n = get()
    print("%s, %s, %s" % (m, s, n))


outer()

You can access global variables using the global keyword.

Answered By: Rohan Mukherjee
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.