2016-08-01 18 views
1

Hier ist ein lustiges. Erstellen Sie eine Datei foo.py mit folgendem Inhalt:Python: Ändern des Wertes in importiertem Diktat hat keine Wirkung

OPTIONS = {'x': 0} 

def get_option(key): 
    from foo import OPTIONS 
    return OPTIONS[key] 

if __name__ == '__main__': 
    OPTIONS['x'] = 1 
    print("OPTIONS['x'] is %d" % OPTIONS['x']) 
    print("get_option('x') is %d" % get_option('x')) 

Lauf python foo.py die folgende Ausgabe gibt:

OPTIONS['x'] is 1 
get_option('x') is 0 

Ich würde das Ergebnis zu erwarten 1 in beiden Fällen zu sein. Warum ist es 0 im zweiten Fall?

+0

Sie haben zwei 'OPTION's,' __main __. OPTIONS' und 'foo.OPTIONS'. – user2357112

+0

OPTIONS in __main__ ist in Locals(), aber OPTIOINS in get_option ist in globals() –

Antwort

2

Sie erhalten, weil from foo import OPTIONS Linie in get_options() Funktion einen neuen lokalenOPTIONS Variable in einem Speicher, dessen Wert lädt ist { 'x': 0}. Aber wenn Sie diese Zeile entfernen/kommentieren, dann haben Sie Ihr erwartetes Ergebnis, weil OPTIONS Variable in get_options() ist jetzt eine globale Variable, kein lokal.

OPTIONS = {'x': 0} 

def get_option(key): 
    # from foo import OPTIONS 
    return OPTIONS[key] 

if __name__ == '__main__': 
    OPTIONS['x'] = 1 
    print("OPTIONS['x'] is %d" % OPTIONS['x']) 
    print("get_option('x') is %d" % get_option('x')) 

Sie können auch debuggen, dass die id() Funktion unter Verwendung, die die „Identität“ eines Objekts zurückgibt während es Lebensdauer ist.

Für, dass die Debugging-Code ist:

OPTIONS = {'x': 0} 

def get_option(key): 
    from foo import OPTIONS 
    print("Id is %d in get_option" % id(OPTIONS)) 
    return OPTIONS[key] 

if __name__ == '__main__': 
    OPTIONS['x'] = 1 
    print("Id is %d in main" % id(OPTIONS)) 
    print("OPTIONS['x'] is %d" % OPTIONS['x']) 
    print("get_option('x') is %d" % get_option('x')) 

Ausgang:

Id is 140051744576688 in main 
OPTIONS['x'] is 1 
Id is 140051744604240 in get_option 
get_option('x') is 0 

Anmerkung: Werte von IDs können auf dem System geändert werden.

Jetzt können Sie die IDs unterscheidet sich sowohl in Ort sehen, bedeutet dies, dass es zwei OPTIONS innerhalb get_options() Funktion ein __main__.OPTIONS und andere ist ist foo.OPTIONS. Aber, wenn Kommentar/Zeile from foo import OPTIONS in get_options() entfernen, erhalten Sie die gleiche ID an beiden Orten.

+0

Sollen nicht Wörterbücher By-Referenz sein? Ich bekomme das gleiche Ergebnis, wenn ich "get_option" in "import foo" ändere. Rückgabe foo.OPTIONS [Schlüssel] '. –

+0

@MichaelHerrmann Ich habe nicht das gleiche Ergebnis erhalten, nachdem ich Änderungen vorgenommen habe. Kannst du Änderungen teilen, um es klar zu verstehen? –

+0

Ich bekomme sie immer noch auf 2.7.6 –

Verwandte Themen