[Tutor] valueOf() equivalent

Darrell Brogdon darrell@brogdon.net
Tue, 19 Dec 2000 22:28:09 -0500


Well, in Java you have the valueOf() method which, as its name sounds, 
will tell you the value of a member (variable).  So in my example I 
could say:

   print tmp_var.valueOf()

...if Python were to have a valueOf() function.

Here's a more complete example that may better explain what I'm trying 
to do:

class myTestClass:
   test_variable   = 2

   def __init__(self):
       self.myTestFunc(self.test_variable, 4)

   def myTestFunc(self, my_var, var_val):
       my_test_var = my_var
       my_test_var = my_test_var + 1

       if my_test_var < var_val:
           print "Yes."
           eval('self.my_var') = my_test_var   # <-- I know this won't 
work but this is why I need a "valueOf()" equivalent.
       else:
           print "No."

my_test = myTestClass()


If you're familiar with PHP, this can be considered using a variable 
variable (http://php.net/manual/language.variables.variable.php).

-Darrell


Kalle Svensson wrote:

> Sez Darrell Brogdon:
> 
>> Is there a Python equivalent to the Java "valueOf()" method?  For 
>> example, I want to be able to determine the value of 'tmp_var' in the 
>> following function:
>> 
>> test_variable = 2
>> 
>> def myTestFunction(tmp_var, count_var):
>>    if( tmp_var == count_var ):
>>        print "Match!"
>>    else:
>>        print "No match"
>> 
>> myTestFunction('test_variable', 5)
> 
> I'm not sure I understand what you mean (don't remember much Java), but
> maybe the built-in function eval() is what you're looking for?
> 
> test_variable = 2
> if eval("test_variable") == 2:
>     print "Yes."
> else:
>     print "No."
> 
> will print Yes.
> 
> But whenever I feel tempted to use eval, I rethink my program instead.  I
> don't feel clean after using eval...
> 
> A bunch of functions you might be interested in are int, float and str.
> int("20") == 20
> float("10.0") == 10.0 # Maybe, you never know with floats...
> str(10) == "10"
> 
> The above example would become:
> 
> test_variable = 2
> if int(test_variable) == 2:
>     print "Yes."
> else:
>     print "No."
> 
> HTH,
>   Kalle