deref in a string into an operand

Steven Bethard steven.bethard at gmail.com
Fri Nov 5 17:22:48 CET 2004


John Doe <atterdan <at> yahoo.com> writes:
> 
> So using a builtin object like 'x' ...
> 
> 	x = 5
> 	attr = '__mul__' 
> 
> 	print x.__getattribute__( attr )( 5 )
> 	25
> 
> My program will store the operand as '__mul__' instead of '*', along with
> a health bit of comment.

You also might consider just storing the operator.<op> methods in an appropriate
dictionary:

>>> import operator
>>> operator_map = {'+':operator.add, '-':operator.sub}
>>> operator_map['+'](1, 2.0)
3.0

This allows you to call the add function whatever you want.

Steve




More information about the Python-list mailing list