callable classes

Hung Jung Lu hungjunglu at yahoo.com
Sat Dec 27 00:47:41 CET 2003


"Duncan Smith" <buzzard at urubu.freeserve.co.uk> wrote in message news:<bshtlg$m1r$1 at news6.svr.pol.co.uk>...
> I recently started to rewrite a class and decided to take a bunch of related
> methods and put them in a separate callable class.  (They're all what I
> would call pointwise operations on pairs of instances, they raise exceptions
> for identical reasons, and they all return a new instance).  It seemed like
> a good idea at the time, but now I'm not so sure.  So my very general
> questions are:
> 
> Is this a reasonable use for a callable class?

Sure. As long as the children callable objects/classes share similar
features that can be factored out to a parent object/class. But one
problem is that Python overloads with () operator with class
constructor.

> In what circumstances are callable classes particularly useful?  (Maybe I
> haven't racked my brains long enough.)

Your case is the representative case. :) The problem isn't with your
line of thought. It is with Python, which has two drawbacks: (a) it's
class-based OOP, instead of prototype-based as languages like Self or
Io. So, usage of classes as objects becomes somewhat cumbersome. (b)
The () operator is overloaded with class constructor call.

The easiest way out is not to use the () operator directly. It is less
confusing if you give it a name, like:

result = my_child_method.process(x1, x2)

Also, it is often easier to separate instances from classes. For your
problem, I would do something like:

class parent(object):
    g = "y = y + 4"
    def process(self, x, y):
        exec self.g
        return self.f(x) + y
    def f(self, x):
        return x

class childA(parent):
    g = "y = y + 7"
    def process(self, x, y):
        result = parent.process(self, x, y)
        return result + 1
    def f(self, x):
        return 3*x
childA = childA() # this converts childA into an object

class childB(parent):
    def process(self, x, y):
        self.g = "y = y + %d" % x
        result = parent.process(self, x, y)
        return result + 2
childB = childB() # this converts childB into an object

print childA.process(1, 2) # prints 13
print childB.process(1, 2) # prints 6

This example shows that you have several ways to customize the
behavior of the children methods. They could be made more specific if
you describe your problem more in detail. But I guess you can figure
out the rest on your own.

regards,

Hung Jung




More information about the Python-list mailing list