class factory example needed (long)

Kent Johnson kent37 at tds.net
Tue Mar 1 14:23:20 EST 2005


Gary Ruben wrote:
> OK, I've managed to get this to work with Rainer's method, but I 
> realised it is not the best way to do it, since the methods are being 
> added by the constructor, i.e. they are instance methods. This means 
> that every time a foo object is created, a whole lot of code is being 
> run. It would be better to do the same thing with class 'static' 
> methods, if this is possible, so that the methods are created just once.
> Is this possible?

Here is a solution using a metaclass:

import Numeric

class MetaFoo(type):
     def __init__(cls, name, bases, d):
         super(MetaFoo, cls).__init__(cls, name, bases, d)
         for u in ['sqrt', 'cos', 'tan']:
             setattr(cls, u, lambda self, uf=getattr(Numeric, u): uf(self.value + 42.0))


class Foo(object):
     __metaclass__ = MetaFoo

     def __init__(self, value):
         self.value = float(value)

f = Foo(7)
print f.sqrt()


Kent



More information about the Python-list mailing list