The Occasional Occurence

42

June 11, 2004 at 10:59 AM | categories: Python

This question came up on the python tutor list:

::

What is the most convincing way to mimick this in Python?

#include stdio .h

#define SIX 1 + 5 #define NINE 8 + 1

int main(void) {
printf("What do you get if you multiply six by nine: %dn", SIX *
NINE);

System Message: WARNING/2 (<string>, line 18)

Definition list ends without a blank line; unexpected unindent.

return 0;

System Message: WARNING/2 (<string>, line 19)

Definition list ends without a blank line; unexpected unindent.

}

I dutifully came up with this answer...

class define:
...         def __init__(self, strnumexpr):
...                 self.val = strnumexpr
...         def __mul__(self, x):
...                 answer = self.val + '*' + x.val
...                 return eval(answer)
...         def __repr__(self):
...                 return str(eval(self.val))
...
>>> SIX = define('1 + 5')
>>> NINE = define('8 + 1')
>>> SIX
6
>>> NINE
9
>>> SIX * NINE
42

You could hide the define class in a module which might make it more convincing...

>>> from hhgtg import define
>>> SIX = define('1 + 5')
>>> NINE = define('8 + 1')
>>> SIX
6
>>> NINE
9
>>> SIX * NINE
42

If you are confused, check the wikiPedia.