deref in a string into an operand

J

John Doe

I've got the action '+' stored as the variable 'plus',
that is plus='+'

Now I want to use the variable plus in an equation:
5 plus 7, just line 5 + 7

How do I do that?

Dan
 
J

John Doe

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.

Dan. Closed.
 
P

Peter Otten

John said:
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:
NotImplemented

Consider using the operator module instead:
2.0

Peter
 
S

Steven Bethard

John Doe said:
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.
import operator
operator_map = {'+':eek:perator.add, '-':eek:perator.sub}
operator_map['+'](1, 2.0)
3.0

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

Steve
 
P

Peter Abel

John Doe said:
I've got the action '+' stored as the variable 'plus',
that is plus='+'

Now I want to use the variable plus in an equation:
5 plus 7, just line 5 + 7

How do I do that?

Dan

If you want a string:
equation = '5 '+plus+' 7'

or

equation = '5 %s 7' % plus

Regards
Peter
 

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,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top