Java Finalize Method similar in python -
i want determine how can determine if object goes out of scope , perform operations when object goes out of scope
in java have finalize method called jvm when object has no more references.
i new python world , want determine if there similar way java finalize can perform operations before , object destroyed or there no more references object
what want called destructor
of object. python has concept using - __del__
method of class.
example -
class footype: def __init__(self, id): self.id = id print self.id, 'born' def __del__(self): print self.id, 'died'
the __del__
method called when object destroyed.
now if define above class inside python file , lets call test.py
, , add following lines below , run python code, following result -
f1 = footype(1) f2 = footype(2) python test.py 1 born 2 born 1 died 2 died
please note, __del__
destructor may not called in circumstances , , more advised use contexts
handling cleanup , etc.
though better way handling cleanup , etc through contexts
, using with
statement . example of with
statement -
with open('file','r') f: <some statements operating on f>
once with
block ends, interpreter calls __exit__
function of variable - called context manager
- responsible cleanup. (in above example , context manager
f
)
you can use contextlib
create custom context managers.
Comments
Post a Comment