adding in-place operator to Python

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Sep 29 21:31:58 EDT 2008


En Thu, 25 Sep 2008 17:04:59 -0300, Arash Arfaee <erexsha at gmail.com>  
escribió:

> Thank you very much Gerhard and Terry.
>
> I am trying to add undefined state to some Boolean operator. Here is  
> what I
> tried to do and It is not working:
>
> class _3ph:
>     def __init__(self):
>         self.value = 0
>
>     def __xor__(self,item):
>         if self.value==2 or item==2:
>              return 2
>         else:
>              return self.__xor__(item)
>
> what I am trying to do is assigning 2 to undefined state and have xor
> operator return 2 if one of inputs are 2.
> it seems Although I defined xor in _3ph class, python treat any object  
> from
> this class just like integer variables.

Because you return a plain integer from __xor__, so the _3ph "magic" is  
lost. Try something like this:

def xor3(v1, v2):
     # this should implement the actual logic
     if v1==2 or v2==2: return 2
     return v1 ^ v2

class _3ph:
     def __init__(self, value=0):
         self.value = value

     def __xor__(self, item):
         if isinstance(item, _3ph):
             return _3ph(xor3(self.value, item.value))
         else:
             return _3ph(xor3(self.value, item))

     __rxor__ = __xor__

     def __repr__(self):
         return '%s(%s)' % (self.__class__.__name__, self.value)

     __str__ = __repr__

a = _3ph(0)
b = _3ph(1)
c = _3ph(2)
print "a    ", a
print "b    ", b
print "c    ", c
print "a ^ a", a ^ a
print "a ^ b", a ^ b
print "a ^ c", a ^ c
print "a ^ 0", a ^ 0
print "a ^ 1", a ^ 1
print "a ^ 2", a ^ 2
print "b ^ a", b ^ a
print "b ^ b", b ^ b
print "b ^ c", b ^ c
print "b ^ 0", b ^ 0
print "b ^ 1", b ^ 1
print "b ^ 2", b ^ 2
print "c ^ a", c ^ a
print "c ^ b", c ^ b
print "c ^ c", c ^ c
print "c ^ 0", c ^ 0
print "c ^ 1", c ^ 1
print "c ^ 2", c ^ 2
print "0 ^ a", 0 ^ a
print "0 ^ b", 0 ^ b
print "0 ^ c", 0 ^ c
print "1 ^ a", 1 ^ a
print "1 ^ b", 1 ^ b
print "1 ^ b", 1 ^ c
print "2 ^ a", 2 ^ a
print "2 ^ b", 2 ^ b
print "2 ^ c", 2 ^ c
print "--- contrast"
print "0 ^ 0", 0 ^ 0
print "0 ^ 1", 0 ^ 1
print "0 ^ 2", 0 ^ 2
print "1 ^ 0", 1 ^ 0
print "1 ^ 1", 1 ^ 1
print "1 ^ 2", 1 ^ 2
print "2 ^ 0", 2 ^ 0
print "2 ^ 1", 2 ^ 1
print "2 ^ 2", 2 ^ 2

(I've kept your _3ph name, but I think it's rather ugly... If the class is  
suposed to be public, its name should not start with an underscore. This  
is a *very* strong naming convention. See PEP8  
http://www.python.org/dev/peps/pep-0008/ for some other stylistic  
recommendations)
You may want to restrict the allowed values in __init__, by example.

-- 
Gabriel Genellina




More information about the Python-list mailing list