List operator overloading snag

Steven Brent stevenbee at removethis.att.net
Sun Apr 25 13:23:13 EDT 2004


Dear Group:

I am a little perplexed by a basic example from the O'Reilly book, 2nd ed.,
which demonstrates overloading some builtin list operators by embedding
lists in a wrapper class.

Below is a snippet which shows the wrapper class and the overloaded
operator definition within (in this case, '__or__')

## BEGIN SNIPPET (from setwrapper.py)

class Set:
    def __init__(self, value = []):
        self.data = []
        self.concat(value)
    
    def union(self, other):
        res = self.data[:]
        for x in other:
            if not x in res:
                res.append(x)
        print 'using Set.__or__' #for debugging
        return Set(res)
   
    def __repr__(self):
        return 'Set: ' + `self.data` #for debugging

    def __or__(self, other):
        return self.union(other)

## END SNIPPET

The problem is that I can't seem to get my wrapped lists to use the
overloaded versions of the operators without calling the customize
instance method directly, as shown below:
>>> import setwrapper; from setwrapper import *

>>> S1 = Set(['s','p','a','m'])
>>> S2 = Set(['s','c','a','t'])

>>> print S1 or S2
Set: ['s', 'p', 'a', 'm'] # custom __repr__ used but still default
                          # __or__ behavior, returns first true operand

>>> print S1.__or__(S2)
using Set.__or__
Set: ['s', 'p', 'a', 'm', 'c', 't'] # now all the custom behaviors

This happens regardless of whether the module is imported into IDLE, or run
standalone. Obviously I'm missing something very basic namespace issue, and
I don't want to gloss over any bumps in my learning curve.

Many thanks.

-- 
**********************
www.emptydrum.com
...like a think tank
without the thinking
or the tank
**********************



More information about the Python-list mailing list