简体   繁体   中英

Variable decleration in a 'try except' block of a recursive function

was trying to declare variable t in the first iteration of a recursion

class c:
    def __init__(self, a):
        self.n=a
def a():
    t=c(5)
    def b():
        print(t.n)
    b()

does print t

def d():
    try:
        t
        print(t.n)
    except:
        t=c(5)
        d()

doenst print t

I don't understand the difference and why in the first function does work and the second doesn't

it won't print t because t is a local variable to each function call and is not recognized in the context of the other calls to d . if you want to use it you either have to make it global or pass it as an argument

def d(t=None):
    try:
        print(t.n)
    except:
        t=c(5)
        d(t=t)
d()

More explanation

(There is a great video about this by mCoding i recommend you watch, and the content of the channel is pretty good)

Why is it local in d but not b ?

What happens is: at compile time python will look at your function and see is t defined anywhere in your function? if yes (the case of d , even if the variable is assigned after it's usage), it will take the value from that scope, if not it will try finding it in the next scope and so on. if it doesn't find it, it will assume it's a global.

for example:

variable = 1
def method_1():
    print(variable)
    variable = 2
method_1()

will throw an error even tho variable is defined in the global scope because the compiler found that we are assigning variable inside the function

on the other hand:

variable = 1
def method_2()
    print(variable)

method_2()

will work because the compiler considers variable global

In the second code, when an exception occurs because t is not defined it moves to the except block, and what does the except block do? It creates a variable called t but it is a local variable to that call of the function on the stack and then calls the function again which does the same thing because when you call the function again a new memory is allocated to that function call on the stack and t is not defined in that function call. Hence, it throws an exception and does the same thing again.

在此处输入图像描述

As you can see in the picture an Infinite number of function calls is made until a stack overflow error happens which leads to the termination of your running program because it never breaks out of the try-except block because each time a function call is made t is defined locally to the function call and make another call which doesn't have t defined in it's scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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