On Dec 3, 10:02 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > En Mon, 03 Dec 2007 19:53:20 -0300, sccs cscs <[EMAIL PROTECTED]> escribió: > > > I am very surprising by the Python interpreter behavior : see code > > I initialize a 'A' and a 'B', and i give a B instance reference to the > > instance A in 'm1' method. I can modify (IN/OUT mode) the 'i' > > attribute ( aB.i = 10 ) , BUT I CANNOT DELETE "aB" into the fonction > > m1 ! the code " del aB " or " aB= None" has no effect. 'aB' still > > exists when m1() is finsihed! WHY ? How can i do that? > > First, read this <http://effbot.org/zone/python-objects.htm> > > > > > class A(object): > > def __init__(self): > > pass > > def m1 (self, aB ): > > aB.i = 10 > > del aB > > print "no more B" > > class B(object): > > def __init__(self,i): > > self.i = i > > def __del__(self): > > print "delete B" > > > aA = A () > > aB = B ( i = 6) > > > unA.m1 (aB ) > > print str( aB .i ) #---> Display 10, aB is not destroy ! > > The "del" statement does NOT delete the object, it only removes the name > from the current namespace (and doing so, it decrements the object's > reference count by one). If that was the last reference to the object, it > becomes a candidate for being garbage collected later. > > __del__ is not used too much. If you want to ensure resource deallocation, > use either a try/finally block or a with statement: > > f = open('filename'): > try > for line in f: > do_something_with(line) > finally > f.close() > > Another alternative, Python 2.5 and up: > > from __future__ import with_statement > > with open('filename') as f: > for line in f: > do_something_with(line) > # there is an implicit f.close() here > > If you want to use __del__ for another purpose, please describe your use > case (what you want to achieve, not how you think you should implement it). > > -- > Gabriel Genellina
(note, you don't want to do this, it's a proof of concept) import sys class A(object): def __init__(self): pass def m1(self, x = None): if x == None: x = sys._getframe(1).f_locals ab = 'aB' x[ab].i = 10 del x[ab] print 'No more B' class B(object): def __init__(self, i): self.i = i def __del__(self): print 'delete B' aA = A() aB = B(i = 6) print str(aB.i) aA.m1() print str(aB.i) Outputs: In python: 6 delete B No more B Traceback (most recent call last): File "del.py", line 23, in <module> print str(aB.i) NameError: name 'aB' is not defined In jython: 6 No more B Traceback (innermost last): File "del.py", line 23, in ? NameError: aB -- http://mail.python.org/mailman/listinfo/python-list