[Edu-sig] Gutless classes

David Handy david at handysoftware.com
Fri Sep 9 19:04:31 CEST 2005


On Thu, Sep 08, 2005 at 03:57:47PM -0700, Kirby Urner wrote:
> > Extending Classes
> > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/412717
> > 
> > --Dethe
> > 
> 
> Thanks for showing me that.
> 
> I guess I'm just fascinated by the mutability of classes at runtime even
> without __metaclass__ magic, e.g.:
> 
> 
>  >>> class Alter(object):  
>         "stub class"
>   	  Pass
> 
>  >>> def meth1(self): return "Meth 1"   # mindless method 1
> 
>  >>> def meth2(self): return "Meth 2"   # I'm mindless too
> 
>  >>> class Alter(object):
> 	pass
> 
>  >>> Alter.m1 = meth1
>  >>> oa = Alter()  # create objects, go wild
>  >>> oa.m1()
>  'Meth 1'
>  >>> ob = Alter()
> 
> Sometime later, rebind the method m1 in the class itself:
> 
>  >>> Alter.m1 = meth2
>  >>> oa.m1()
>  'Meth 2'
>  >>> ob.m1()
>  'Meth 2'

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


More information about the Edu-sig mailing list