How do I define a __del__ method for an object?
Uwe Grauer
news at grauer-online.de
Sun Mar 7 17:06:13 EST 2004
Stewart,
__del__ is used for object destruction.
Read:
http://python.org/doc/current/ref/customization.html#l2h-175
Uwe
Stewart Midwinter wrote:
> I was looking through Swaroop's tutorial, "A Byte of Python", on Python
> objects,(http://www.python.g2swaroop.net/), and he mentions that you can
> define a __del__ function to completely delete object instances.
> However, when I try to define one in the attached script, not just one,
> but all, of the defined objects disappear.
>
> Can someone show me how to define a __del__ object that works on only
> one object instance?
>
> Thanks
> Stewart
>
>
> ------------------------------------------------------------------------
>
> #!/usr/bin/python
> # Filename: objvar.py
> # from Swaroop's A Byte of Python,
> # http://www.python.g2swaroop.net/byte/ch11s05.html
>
> class Person:
> '''class Person represents a person.'''
> population = 0
>
> def __init__(self, name):
> '''Initializes the person.'''
> self.name = name
> print '(Initializing %s)' % self.name
>
> # When this person is created,
> # he/she adds to the population
> Person.population += 1
>
> def sayHi(self):
> '''Method sayHi greets the other person.
> Really, that's all it does.'''
> print 'Hi, my name is %s.' % self.name
>
>
> def howMany(self):
> '''Prints the current population.'''
> # There will always be atleast one person
> if Person.population == 1:
> print 'I am the only person here.'
> else:
> print 'We have %s persons here.' % \
> Person.population
>
> def sayDie(self):
> '''when a person dies,
> she reduces the population by one,
> but she is still remembered.'''
> print self.name, 'has died.'
> Person.population -= 1
>
>
>
> swaroop = Person('Swaroop')
> swaroop.sayHi()
> swaroop.howMany()
>
> kalam = Person('Abdul Kalam')
> kalam.sayHi()
> kalam.howMany()
>
> swaroop.sayHi()
> swaroop.howMany()
>
> kalam.sayDie()
> kalam.howMany()
> #kalam.__del__('Abdul Kalam')
> abdul = Person('Abdul')
> abdul.sayHi()
> abdul.howMany()
> print kalam.sayHi.__doc__
> print Person.__doc__
More information about the Python-list
mailing list