Is it possible to modify variable in python that i

2020-01-27 03:06发布

Given following code:

def A() :
    b = 1

    def B() :
        # I can access 'b' from here.
        print( b )
        # But can i modify 'b' here? 'global' and assignment will not work.

    B()
A()

For the code in B() function variable b is in outer scope, but not in global scope. Is it possible to modify b variable from within B() function? Surely I can read it from here and print(), but how to modify it?

9条回答
对你真心纯属浪费
2楼-- · 2020-01-27 03:49

For anyone looking at this much later on a safer but heavier workaround is. Without a need to pass variables as parameters.

def outer():
    a = [1]
    def inner(a=a):
        a[0] += 1
    inner()
    return a[0]
查看更多
Anthone
3楼-- · 2020-01-27 03:56

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

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-01-27 03:57

You can, but you'll have to use the global statment (not a really good solution as always when using global variables, but it works):

def A():
    global b
    b = 1

    def B():
      global b
      print( b )
      b = 2

    B()
A()
查看更多
登录 后发表回答