Overloading the ">>" operator in Python 2.2.1
Jp Calderone
exarkun at meson.dyndns.org
Thu Sep 12 09:06:14 EDT 2002
On Thu, Sep 12, 2002 at 08:22:07PM +1200, Andy Elvey wrote:
> Hi all .
> I'm using Python 2.2.1 under Win98. I'm doing some experimenting with
> parsing, and as part of that, I'm trying to overload the right-shift
> operator (>>) so that I can use it as follows (testing against a sequence
> that I read in) -
> a >> b would mean "a is followed by b" .
> So, you could have a function like seqtest("string_to_test" ,
> "foo">>"bar" ) , and that function would return true or false, depending on
> whether foo was followed by bar.
> ( I know it's possible to use regexes for this, but being able to create
> a sequence-testing operator like this would be useful .)
> Many thanks in advance ......
>
>>> class Foo:
... def __rshift__(self, other):
... print 'rshift'
... def __lshift__(self, other):
... print 'lshift'
...
>>> f = Foo()
>>> f >> 'hello'
rshift
>>> f << 'world'
lshift
Also:
>>> dir(42)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__',
'__delattr__', '__div__', '__divmod__', '__doc__', '__float__',
'__floordiv__', '__getattribute__', '__hash__', '__hex__', '__init__',
'__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__',
'__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__',
'__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__',
'__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__',
'__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',
'__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__',
'__truediv__', '__xor__']
Jp
--
It is practically impossible to teach good programming style to
students that have had prior exposure to BASIC: as potential
programmers they are mentally mutilated beyond hope of
regeneration. -- Dijkstra
--
9:00am up 114 days, 9:53, 4 users, load average: 0.02, 0.01, 0.00
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 248 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20020912/37a3bbca/attachment.sig>
More information about the Python-list
mailing list