Re: What's the life time of the variable defined in a class function?



人言落日是天涯,望极天涯不见家 wrote:

Please see the followed example:
class A:
def __init__(self):
pass

class X:
def __init__(self):
n = 200
if True:
j = 200
m = j
k = A()
print m, j

a = X()
# ?? what about the m, n and j? is it still alive?
del a

--------------------------
In C/C++, the life time of m,n and j was the nearest block. but
obviously, python doen't have this syntax, but I would like to know
that whether the life time of m, n, j is base on function range or
the object range.

We can not access the m, n, and j from the outside of class X. Now I'm
writing a program base on the wxpython. In the __init__ function of
wx.Panel, I use normal varable(just like the m,n and j) created some
widgets. It could be show in the window. Does it indicated the life
time of varable m,n,j is base on the object range?

Python has no variables. It has objects, which can be bound to names. Each
binding to a name will increase a reference counter. Each unbinding will
decrease it. so

a = SomeObject()
b = a
del a

will result in the SomeObject-instance still be alive. But when you add

del b

it will be garbage collected.

Now in your example A() bound to k will not survive the exit of the method,
as that means that k goes out of scope, and the object is bound to - the
A-instance - gets its reference-counter decreased, resulting in it being
freed.

The wxwidgets example though is a different thing. If the panel stores a
reference to the object, e.g. via a list (being part of a list or dict also
increases the reference count), it will be kept around.

Diez
.



Relevant Pages

  • Re: Whats the life time of the variable defined in a class function?
    ... time of varable m,n,j is base on the object range? ... Python has no variables. ... binding to a name will increase a reference counter. ...
    (comp.lang.python)
  • Re: What does "del" actually do?
    ... Calvin Spealman wrote: ... In particular, when "del" is applied to a class object, what happens? ... Except, of course, when you aren't deleting names but elements of some container object. ... Since each instance of a class contains a reference to the class, the class will live on even after it is deleted by name, being garbage-collected only after all instances have ceased to exist. ...
    (comp.lang.python)
  • Re: Remove items from a list
    ... Egbert Bouwman wrote: ... >> I must be doing something wrong, but it acts as though it is.... ... One use of `del` is to remove a name from a namespace, ... reference to the object that was the i'th item in the list ...
    (comp.lang.python)
  • problem with weakref.proxy
    ... I'm a completly Python newbie. ... When I add a reference of the new created object in the constructor ... So now my instances are deleted really deleted when I use 'del', ... Exception exceptions.ReferenceError: 'weakly-referenced object no ...
    (comp.lang.python)