Overload del operator

__del__ is a destructor


class Life:#   w w  w.j  av  a2  s . c  o  m
    def __init__(self, name='unknown'):
        print 'Hello', name
        self.name = name
    def __del__(self):
        print 'Goodbye', self.name

brian = Life('A')
brian = 'B'

del brian

The code above generates the following result.

Class Employee with class attribute count.


class Employee:# from   ww w.ja  va 2  s  . c o m
   count = 0       
   
   def __init__( self, first, last ):
      self.firstName = first
      self.lastName = last

      Employee.count += 1

      print "Employee constructor for %s, %s" % ( self.lastName, self.firstName )

   def __del__( self ):
      Employee.count -= 1

      print "Employee destructor for %s, %s" % ( self.lastName, self.firstName )


print "Number of employees before instantiation is", Employee.count

# create two Employee objects
employee1 = Employee( "A", "C" )
employee2 = Employee( "B", "D" )
employee3 = employee1

print "Number of employees after instantiation is", employee1.count

# explicitly delete employee objects by removing references
del employee1
del employee2
del employee3

print "Number of employees after deletion is", Employee.count

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules