[Tutor] valueOf() eqivalent

Alan Gauld alan.gauld@freenet.co.uk
Tue, 26 Dec 2000 15:27:40 +0000


> Is there a Python equivalent to the Java "valueOf()" method?  

First there is no single valueOf() method in Java rather it is part of
the object protocol there being one static method per type. 
The direct equivalent in python are the conversion functions:

str() int() etc.

Usually you don't need them as often as you need valueOf() in 
Java because of Pythons intelligent dynamic typing.


> 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)

Assuming those are backquotes above to convert 2(a number) 
to "2"(a string) you can convert back again with:

    if int(tmp_var) == count_var

If you don't know the type of count_var you could do 
something like:

    count_t = type(count_var)
    if count_t == type(1):   # integer
       tmp2 = int(tmp_var)
    elif count_t == type("s"):  # string
       tmp2 = str(tmp_var)
    elif count_t == type(1.0):  # float
	 tmp2 = float(tmp_var)
etc... then

    if tmp2 == count_var: ...

I suspect there's a cleverer way of doing this using Python's 
introspection capabilities but I leave the exprerts to tell 
us how :-)

Alan g.