[Tutor] empty class methods

Kent Johnson kent37 at tds.net
Wed Dec 14 13:16:45 CET 2005


david wrote:
>  
>  
> class foo:
>     def sayhi(self):
>         print 'hello world'
>     def saybye(self): ##is there any reason for this to be here?
>         pass

Is foo.saybye() a default implementation or a placeholder for an 'abstract' method?

A base class can have a default implementation of a method. The default is used if 
subclasses don't override it. In some cases a do-nothing default such as this one might be 
appropriate, for example if the method is a hook that subclasses override to provide 
specialized behaviour.

A base class can have an empty implementation of a method that is there as a marker 
saying, "subclasses must define this". In this case, a better implementation is
   def saybye(self):
     raise NotImplementedError, "Subclasses must define saybye()"

which clearly shows the intent and will cause a run time error if a subclass omits the 
definition of saybye().

Kent
>  
> class bar(foo):
>     def saybye(self):
>         print 'bye now'
>  
> class baz(foo):
>     def saybye(self):
>         print 'later tater'
>  
> x = foo()
> y = bar()
> z = baz()
>  
> x.sayhi()
> y.sayhi()
> y.saybye()
> z.sayhi()
> z.saybye()
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor




More information about the Tutor mailing list