0

Coming from a C/C++ background, I'm very unfamiliar with these rules in Python. If I create a new list in a python function, assign it as the member variable of some class, when the function ends, does the list go away? (In C/C++, the answer is yes unless there is some sort of dynamic allocation involved, but as I understand it, Python does it...automagically?)

Example:

class C:
    def __init__(self, x):
        self.val = x
        self.l = []

class A:
    def caller(self):
        c_inst = someFunc()
        print c_inst.l

    def someFunc(self):
        blah = C('name')
        blah_l = [1,2,3,4,5]
        blah.l = blah_l
        return blah

What would be printed out inside the caller() function? Would it be [1,2,3,4,5]?

martineau
  • 119,623
  • 25
  • 170
  • 301
stack smasher
  • 443
  • 3
  • 10
  • Briefly: `c_inst` is a local variable. After the function ends, it's gone. – TigerhawkT3 Oct 08 '16 at 00:25
  • In that case, how do I make it stay? Since there's no python equivalent of dynamic allocation? – stack smasher Oct 08 '16 at 00:26
  • Assign it as an instance variable with `self.c_inst = someFunc()`. It will persist as long as that object of class `A` does. – TigerhawkT3 Oct 08 '16 at 00:27
  • To clarify, the instance of class `C` is gone, because it was never saved as anything but a local variable. `self.l`, however, persists as long as the instance of class `A` does, because it was saved as an instance variable. – TigerhawkT3 Oct 08 '16 at 00:28
  • My question was meant as more in the case of we are still inside the function "Caller()", but someFunc() has returned. Would I still be able to access c_inst.l? Maybe I'll clarify with an edit... – stack smasher Oct 08 '16 at 00:30
  • As long as you're still in that function, you can access local variables in it. – TigerhawkT3 Oct 08 '16 at 00:30
  • so the answer to the updated question is "yes"? As long as some pointer to the list still exists, it wont go away? – stack smasher Oct 08 '16 at 00:32
  • You never assigned a `c_inst.l`. You did `self.l = blah_l`, while in the `A` class, which means you'd have to `print self.l`. If you want that `C` class object `c_inst` to have an instance attribute that refers to that list, you'd have to do `blah.l = blah_l`. – TigerhawkT3 Oct 08 '16 at 00:33
  • And now, yes, it will print that list. ...Why don't you try running your code? It's a great way to experiment and discover. – TigerhawkT3 Oct 08 '16 at 00:35
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/125215/discussion-between-staksmashr-and-tigerhawkt3). – stack smasher Oct 08 '16 at 00:35

0 Answers0