[Edu-sig] Gutless classes

Dethe Elza delza at livingcode.org
Fri Sep 9 19:50:20 CEST 2005


On 9-Sep-05, at 10:04 AM, David Handy wrote:

> I haven't yet found any need to change the method on a class, but I  
> have
> often written code that changes a method on an instance. Here's a  
> class that
> "runs" something, but it is an error to run it more than once:
>
> class RunOnce:
>
>     def run(self):
>         self.run = _noMoreRunning
>         # do other stuff that you only want to happen once
>
>     def _noMoreRunning(self):
>         raise Exception("Can only call run() once.")
>
> I prefer the pattern above to the alternative:
>
> class RunOnce:
>
>     def __init__(self):
>         self.__has_been_run_before = False
>
>     def run(self):
>         if self.__has_been_run_before:
>             raise Exception("Can only call run() once.")
>         self.__has_been_run_before = True
>         # do other stuff that you only want to happen once
>
> David H

Yes, this is called "trampoline style."  It can make code hard to  
read if it's over-used, but it's quite nice once in a while.  I tend  
to use this style more in Javascript than in Python, but not for any  
obvious reason.

I think the idea of changing a class after it has been defined is  
more for extending the class with additional methods, rather than  
changing the methods it has.  In Objective-C this type of extension  
is called a Category and it is explicitly supported by the language.   
The idea is that sometimes instead of subclassing, all you really  
want to do is add a couple of methods to an existing class.  In  
Objective-C you can only add methods, not properties, but in Python  
you can do both.

--Dethe

"No lesson seems to be so deeply inculcated by experience of life as  
that you should never trust experts.  If you believe doctors, nothing  
is wholesome; if you believe theologians, nothing is innocent; if you  
believe soldiers, nothing is safe."

         --Lord Salisbury, 19th century British prime minister


-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2488 bytes
Desc: not available
Url : http://mail.python.org/pipermail/edu-sig/attachments/20050909/e1f0c5b7/smime.bin


More information about the Edu-sig mailing list