简体   繁体   中英

Declaring global inside a function

Lately, I've had to write functions that look like this:

fruits = []
def foo():
    global fruits
    ...

What exactly does the line global fruits do? I apologize if this question has been asked before, but I could not find one like this.

It tells the compiler that binding the name should be performed in the module scope rather than the local scope. It has no use if you're simply mutating the object (eg fruits.append('apple') ).

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