Saturday, January 07, 2006

Furthering my investigations into metaprogramming in Python, I just confirmed something I was starting to suspect but wasn't sure of. You can define local parameterized classes inside functions too.


def factory(f) :

class G :

def __init__(self, name) :
self.name = name
f(self)

def __str__(self) :
return self.name

return G


def p(y) :
print y

def q(y) :
print y.name.upper()

A = factory(p)
B = factory(q)

l = A('john')
m = B('jane')



The class "G" is defined inside the function "factory". The constructor calls the function "f" which is itself a parameter to the factory. Hence, every time I call the factory with a different function as argument, I get a new class whose constructor calls that function.

OK, so I'm not sure what this is going to be useful for. After all, reusing class definitions with minor variations is what inheritance is all about. :-)

But I'm thinking again about the horrendous mess that is Optimaes.

Optimaes features several types of agents who differ only in their negotiating and exchange strategies. They're all derived by inheritance from a basic Agent class. But somehow the code for this is awkward and hard to read.

Might there be a more elegant solution using a parameterized class technique?

Also, are there solutions to Dependency Injection problems here?

Let's see if I can come up with a more compelling example.

No comments: