1

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
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Sean Wilkinson
  • 111
  • 2
  • 7
  • 1
    No, Python *never* copies an object unless you explicitly tell it to. Please see [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html), which was written by SO veteran Ned Batchelder. – PM 2Ring Sep 25 '18 at 06:37
  • 1
    You should read about mutable vs immutable objects in Python – dojuba Sep 25 '18 at 06:44
  • Thanks, I learnt something today, sorry for the duplicate question. – Sean Wilkinson Sep 25 '18 at 06:54
  • Read about [are-static-class-variables-possible](https://stackoverflow.com/questions/68645/are-static-class-variables-possible) – stovfl Sep 25 '18 at 06:59

0 Answers0