Abstract classes?

Daniel T. danielt3 at gte.net
Wed Feb 16 23:05:27 EST 2000


I was re-reading Design Patterns with an eye toward implementing some of
them in Python and I have a question about Abstract classes. In the code
below I have an Observer pattern set up. Since Python isn't strongly
typed, there is no need for the abstract Observer class but I put one in
anyway to make clear what Subject expects of Observers. What does the
Python community in general think of this?
Also, any general critiques of this code?

class Observer:
   def update( self ):
      raise "sub-classes must over-ride this method"
      
class Subject:
   " Something that is being observered by 0..* observers "
   def __init__( self ):
      self.__observers = {}
      
   def has_observer( self, observer ):
      " returns true if observer is in notification list "
      return self.__observers.has_key( observer )
         
   def notify( self ):
      " sub-classes should call this when their state changes "
      for observer in self.__observers.keys():
         observer.update( self )
      
   def attach( self, observer ):
      " add observer to notification list "
      self.__observers[ observer ] = 1
      
   def detach( self, observer ):
      " remove observer from notification list "
      del self.__observers[ observer ]
      
class GenericSubject( Subject ):
   def __init__( self ):
      self.__value = 0

   def set_value( self, value ):
      self.__value = value
      notify()
      
   def get_value( self, value ):
      return value
      
class GenericObserver( Observer ):
   def update( self, subject ):
      print subject.get_value()

-- 
When a thing ceases to be a subject of controversy,
it ceases to be a subject of interest.
                                                   -- William Hazlitt



More information about the Python-list mailing list