How to redirect operation methods to some sepcific method easily?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Aug 3 07:08:07 EDT 2008


On Sun, 03 Aug 2008 02:44:34 -0700, Victor Lin wrote:

> Now, here comes the problem : I have to override all the operation
> methods, such as __add__ and __mul__. I know the most stupid way is just
> to write all of them like this.
> 
> def __add__(self, other):
>      self.leftOperation('add', other)
> 
> def __mul__(self, other):
>      self.leftOperation('mul', other)
> 
> But I don't want to do that in this stupid way. I want to use little
> code to redirect these operation methods to some specific method with
> it's name.
> 
> What can I do?


I usually dislike code that uses exec, but this is one place where I'm 
tempted to make an exception (mainly because I can't think of an 
alternative). Untested and at your own risk:

def factory(name):
    """Return a method name and a function."""
    def func(self, other):
        return self.LeftOperation(name, other)
    return "__%s__" % name, func


class Parrot(object):
    for name in ["mul", "add", "sub", "pow"]: # and many more...
        name, f = factory(name)
        exec "%s = f" % name
    del name, f


Urrggh. I feel dirty. *wink*



-- 
Steve



More information about the Python-list mailing list