deref in a string into an operand
Peter Otten
__peter__ at web.de
Fri Nov 5 06:11:41 EST 2004
John Doe wrote:
> Foolish me; I examined the __builtin__ and found __getattribute__,
> along with '__mul__' '__add__', '__sub__' and '__div__'.
>
> 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.
However, this may sometimes fail:
>>> 1 + 1.0
2.0
>>> 1 .__add__(1.0)
NotImplemented
Consider using the operator module instead:
>>> import operator
>>> operator.add(1, 1.0)
2.0
>>> getattr(operator, "add")(1, 1.0)
2.0
Peter
More information about the Python-list
mailing list