How come foo doesn't update in myClass2 using a bool (Example 1) but it works if I use a list (example 2). I'm guessing to save memory the interpreter uses a reference when passing a list but makes a copy when using bools, ints, etc? how can I pass a refrence instead? I am trying to avoid using global. (Python 3.7.0)
Example 1
class myClass1():
def __init__(self, foo):
self.foo = foo
def run(self):
print(self.foo)
self.foo = False
class myClass2():
def __init__(self, foo):
self.foo = foo
def run(self):
print(self.foo)
def main():
foo = True
c1 = myClass1(foo)
c2 = myClass2(foo)
c1.run()
c2.run()
if __name__ == '__main__':
main()
Output
True
True
Example 2
class myClass1():
def __init__(self, foo):
self.foo = foo
def run(self):
print(self.foo[0])
self.foo[0] = False
class myClass2():
def __init__(self, foo):
self.foo = foo
def run(self):
print(self.foo[0])
def main():
foo = [True]
c1 = myClass1(foo)
c2 = myClass2(foo)
c1.run()
c2.run()
if __name__ == '__main__':
main()
Output
True
False