Definition of class Date. : Class Definition « Class « Python Tutorial






class Date:
   daysPerMonth = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]

   def __init__( self, month, day, year ):
      if 0 < month <= 12:   
         self.month = month
      else:
         raise ValueError, "Invalid value for month: %d" % month

      if year >= 0:         
         self.year = year
      else:
         raise ValueError, "Invalid value for year: %y" % year
      
      self.day = self.checkDay( day )   

      print "Date constructor:",
      self.display()

   def __del__( self ):
      print "Date object about to be destroyed:",
      self.display()

   def display( self ):
      print "%d/%d/%d" % ( self.month, self.day, self.year )

   def checkDay( self, testDay ):
      if 0 < testDay <= Date.daysPerMonth[ self.month ]:
         return testDay
      elif self.month == 2 and testDay == 29 and ( self.year % 400 == 0 or self.year % 100 != 0 and self.year % 4 == 0 ):
         return testDay
      else:
         raise ValueError, "Invalid day: %d for month: %d" % ( testDay, self.month )








11.9.Class Definition
11.9.1.Demonstrates a basic class and object
11.9.2.Creating a Class (Class Definition)
11.9.3.Classes and Types
11.9.4.Defining Class Methods with the def Statement
11.9.5.Rectangle class
11.9.6.Throwing Methods Around
11.9.7.Simple definition of class Time.
11.9.8.Definition of class Date.