Die globale Python-Variable wird nicht aktualisiertPython

Python-Programme
Anonymous
 Die globale Python-Variable wird nicht aktualisiert

Post by Anonymous »

Ich versuche, eine globale Variable in einem Programm zu verwenden, erhalte jedoch unerwartete Ergebnisse. Beispielcode ist unten dargestellt. Ich habe versucht, das Problem auf seine einfachsten Bestandteile zu reduzieren.
Datei a.py:

Code: Select all

class Foo:
def __init__(self, s1: str, s2: str):
self.s1 = s1
self.s2 = s2

def __str__(self):
return f'Foo(s1="{self.s1}", s2="{self.s2}")'

foo = Foo('first', 'second')

def set_foo(new_foo: Foo):
global foo
foo = new_foo
print('Setting foo', foo)
Datei b.py:

Code: Select all

from a import foo, Foo, set_foo

def tfunc():
print('Old foo', foo)
new_foo = Foo('third', 'fourth')
set_foo(new_foo)
print('New foo', foo)
print(foo == new_foo)

tfunc()
Wenn ich das Programm ausführe, erhalte ich folgende Ergebnisse:

Code: Select all

>python b.py
Old foo Foo(s1="first", s2="second")
Setting foo Foo(s1="third", s2="fourth")
New foo Foo(s1="first", s2="second")
False
Warum wird foo in der Funktion tfunc nicht auf den neuen Wert gesetzt?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post