简体   繁体   中英

Changing a variable of one function from another function

Is there a way to change a variable inside function A from function B when function A called function B

For example:

def a():
     flag = False
     b()
     print(flag)

def b():
     flag = True

I would like flag == True

another example:

def a():
    list = [1,2,3]
    b():
    return list

 def b():
    list.append(4)

The flag variable is locally scoped to function A and B. This does not mean that they are the same variable. They're completely different from each other, occupying a completely different address space all together.

If you would like function B to change the value of your flag variable in function A, you can simply have function B return the value.

def b():
   flag = True 
   return flag

Another method is to use pass by reference, which allows you to alter the value of the variable in that memory address space. This only works for mutable objects. In this case, a boolean is immutable so a pass by reference isn't possible here.

you need to pass it either as a parameter to the function or create a global variable (usually considered to be bad style)

flag = False


def a(): 
    b()
    print(flag)


def b():
    global flag
    flag = True
    
a()  # True

I would consider creating a class for that. In this way instead of following a global variable, you just need to track the object:

class flagChangerClass():
    def __init__(self):
        self.flag = False

    def a(self):
        self.b()
        print(self.flag)

    def b(self):
        flag = True

That way you can call it after initializing the object:

flagChanger = flagChangerClass() #Equivalent to flag = False
flagChanger.a() # Changes flag by calling function b in class

If you want with the list:

class listChangerClass():
    def __init__(self):
        self.internalList = [1,2,3]

    def a(self):
        self.b()
        print(self.internalList )

    def b(self):
        self.internalList.append(4)

listChanger = listChangerClass()
listChanger.a()
print(listChanger.internalList)

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