Commutative object in emulating numbers

I

iu2

Hi,

I reached the chapter "Emulating numeric types" in the python
documentation and I tried this:
def __mul__(self, a):
return 'A' * a

Now, this works as expected:'AAA'

But this doesn't (also as expected):
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
 
I

iu2

Hi,

I reached the chapter "Emulating numeric types" in the python
documentation and I tried this:


        def __mul__(self, a):
                return 'A' * a

Now, this works as expected:>>> a = A()

'AAA'

But this doesn't (also as expected):


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'
 
C

Chris Rebert

Hi,

I reached the chapter "Emulating numeric types" in the python
documentation and I tried this:

       def __mul__(self, a):
               return 'A' * a

Now, this works as expected:
'AAA'

But this doesn't (also as expected):

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?

You need to define __rmul__():
http://docs.python.org/dev/3.0/reference/datamodel.html#object.__rmul__

Cheers,
Chris
 
S

Steven D'Aprano

Hi,

I reached the chapter "Emulating numeric types" in the python
documentation and I tried this: [...]
What do I need to do in order to make the two classes, int and A,
commutative?


Try adding a __rmul__ method:


class A:
def __mul__(self, a):
return 'A' * a
__rmul__ = __mul__
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top