Python language problem

Laszlo Nagy gandalf at designaproduct.biz
Wed Jun 7 07:18:55 EDT 2006


ripleyfu at gmail.com i'rta:
>>>> class A:
>>>>         
> ...   pass
> ...
>   
>>>> a = A()
>>>> b = a
>>>> del b
>>>> a
>>>>         
> <__main__.A instance at 0x00B91BC0>
> I want to delete 'a' through 'b', why It does't? 
> How can I do that?
>
>   
You must undestand that 'a' and 'b' are names. You can only delete 
names, not objects. Objects are freed by the garbage collector, 
automatically. Probably you used to write programs in C or Pascal or 
other languages with pointers. In Python, there are no pointers, just 
references and you cannot free an object. You can only delete the 
references to it. The good question is: why would you like to free an 
object manually? The garbage collector will do it for you automatically, 
when the object has no more references. (Well, cyclic references are 
also garbage collected but not immediately.)

If you need to handle resources, you can still use the try-finally 
statement. Like in:

f = file('example.txt','r')
try:
s = f.read()
finally:
f.close() # The resource is freed. But the object that was used to 
access the resource, may not be freed here....

Regards,

Laszlo





More information about the Python-list mailing list