Is it possible to modify variable in python that is in outer, but not global, scope?

前端 未结 9 1970
温柔的废话
温柔的废话 2020-11-30 02:55

Given following code:

def A() :
    b = 1

    def B() :
        # I can access \'b\' from here.
        print( b )
        # But can i modify \'b\' here? \'         


        
9条回答
  •  猫巷女王i
    2020-11-30 03:30

    I don't know if there is an attribute of a function that gives the __dict__ of the outer space of the function when this outer space isn't the global space == the module, which is the case when the function is a nested function, in Python 3.

    But in Python 2, as far as I know, there isn't such an attribute.

    So the only possibilities to do what you want is:

    1) using a mutable object, as said by others

    2)

    def A() :
        b = 1
        print 'b before B() ==', b
    
        def B() :
            b = 10
            print 'b ==', b
            return b
    
        b = B()
        print 'b after B() ==', b
    
    A()
    

    result

    b before B() == 1
    b == 10
    b after B() == 10
    

    .

    Nota

    The solution of Cédric Julien has a drawback:

    def A() :
        global b # N1
        b = 1
        print '   b in function B before executing C() :', b
    
        def B() :
            global b # N2
            print '     b in function B before assigning b = 2 :', b
            b = 2
            print '     b in function B after  assigning b = 2 :', b
    
        B()
        print '   b in function A , after execution of B()', b
    
    b = 450
    print 'global b , before execution of A() :', b
    A()
    print 'global b , after execution of A() :', b
    

    result

    global b , before execution of A() : 450
       b in function B before executing B() : 1
         b in function B before assigning b = 2 : 1
         b in function B after  assigning b = 2 : 2
       b in function A , after execution of B() 2
    global b , after execution of A() : 2
    

    The global b after execution of A() has been modified and it may be not whished so

    That's the case only if there is an object with identifier b in the global namespace

提交回复
热议问题