Why does python behave this way with variables?

前端 未结 2 1281
自闭症患者
自闭症患者 2020-12-18 02:54

I have been trying to understand why python behaves this way, in the block of code below. I have done my research but couldn\'t find a good answer so I came here to see if a

2条回答
  •  忘掉有多难
    2020-12-18 03:36

    Your var is defined as a global variable. In each function when you're only reading the var you're accessing the global var, but the moment there's an assigned value to var somewhere in the function, python treats every var within the function as a local variable. Thus why your last function failed, because print(var) (the local varaible) was called before var = 8 was assigned.

    You can read up a bit about more in these threads:
    How bad is shadowing names defined in outer scopes?
    Python nonlocal statement

    The best thing to do is be explicit about your code so it's no longer confusing if you're trying to reference a local, nonlocal or global variable.

    In this case, assuming your intention is to keep using the global var, do this:

    var = 5
    
    def func1():
        print(var)
    func1()
    
    def func2():
        global var
        var = 8
        print(var)
    func2()
    
    def func3():
        global var
        print(var)
        var = 8  # technically this is not necessary any more var = 8 was already assigned when func2() is called
    func3()
    

    The output is thus:

    5
    8
    8
    

    Edit: Thanks to juanpa.arrivillaga's comment - I missed your original question.

    How could I use a predefined global variable in a function, then define a local variable with the same name inside of the same function, without changing the value of the global variable ? ( in python of course )

    The short answer is - define the local var first like you did in func2() and you're good. The longer answer though is - why would you want to do that? It creates confusion and becomes a headache to track which is when you have variables of the same name in different scope. A better approach would be name your local var to be local_var or something so it's distinctly different and easily traced.

提交回复
热议问题