Commutative object in emulating numbers

iu2 israelu at elbit.co.il
Mon Sep 14 00:54:05 EDT 2009


On Sep 14, 7:52 am, iu2 <isra... at elbit.co.il> wrote:
> Hi,
>
> I reached the chapter "Emulating numeric types" in the python
> documentation and I tried this:
>
> >>> class A:
>
>         def __mul__(self, a):
>                 return 'A' * a
>
> Now, this works as expected:>>> a = A()
> >>> a * 3
>
> 'AAA'
>
> But this doesn't (also as expected):
>
> >>> 3 * a
>
> Traceback (most recent call last):
>   File "<pyshell#45>", line 1, in <module>
>     3 * a
> TypeError: unsupported operand type(s) for *: 'int' and 'instance'
>
>
>
> What do I need to do in order to make the two classes, int and A,
> commutative?
> (In the same way that string and int are commutative over "*")
> Thanks

By commutative I mean give the same result, that is
3 * a
will also return 'AAA'



More information about the Python-list mailing list