On Tue, 12 Apr 2016 08:44 am, John Pote wrote: > On 10/04/2016 04:52, Chris Angelico wrote: >> On Sun, Apr 10, 2016 at 1:46 PM, fan nie <niefa...@gmail.com> wrote: >>> -- >>> https://mail.python.org/mailman/listinfo/python-list >> Sure. I presume you mean something like this: >> >> class Thing: >> things = [] >> def __init__(self): >> self.things.append(self) >> def __del__(self): >> # Remove me when I'm dead >> self.things.remove(self) >> >> This ingenious technique guarantees that you never have dead objects >> in your list, by having each object remove itself when it dies. >> >> ChrisA > I'm not quite sure how tongue in cheek ChrisA's reply and the Thing > class was
I'm sure it was extremely tongue in cheek. > but it did make me think and wonder if my understanding of > Python lore was quite right. To my mind it looks like a Zombie or even > Revenant class. > > If all external references to an instance of Thing are deleted there is > still the reference from the class list 'things []'. In which case will > not this prevent the instance from being garbage collected and __del__() > never called on the dead instance and its memory never released. Correct. > But a > memory dump could reveal the ghost of the instance. On the other hand a > code wizard with the right lore could resurect the instance by getting > the reference to it and bring it back to life - > revenant = Thing.things[x] > > But then I notice 'things' is used as an instance attribute rather than > a class attribute. All seems to be shrouded in a web of mystery Your first analysis was correct. "self.things" is actually a class attribute, despite being accessed from "self". The reason being, attribute lookups look for: - instance attributes; - class attributes; - superclass attributes; in that order. (This is actually an extremely simplified view, but close enough for what we're discussing.) Hence "self.things" will return the same list each time, the one defined as a class attribute, regardless of which "self" does the lookup. If a method were to assign to the attribute, for example "self.things = []", that would create an instance attribute, but that doesn't happen. -- Steven -- https://mail.python.org/mailman/listinfo/python-list