How do I define a __del__ method for an object?
christofer
chris at misery.net
Sun Mar 7 17:47:11 EST 2004
Stewart Midwinter <stewartNO at SPAMmidtoad.homelinux.org> wrote in message news:<404B7893.8060408 at SPAMmidtoad.homelinux.org>...
> #!/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__
>
> --
define this method (a destructor) in your class:
def __del__(self):
do whatever here...
More information about the Python-list
mailing list