How to convert the type of an object by type?

I have:

x = float(1.0)
y = int(2)

t1 = type(x)
t2 = type(x).__name__

If I print t1and t2, I see the following:

print t1
>>> <type 'float'>

print t2
>>> float

How to use t1or t2to change yto the type floatwith the least amount of code?

+4
source share
4 answers

You can do the following:

x = float(1.0)
y = int(2)

y = type(x)(y)
print(type(y))

Exit

float

If you need to do this with a type name, just assign the type to the xvariable and use it as a function:

x = float(1.0)
y = int(2)

t = type(x)
y = t(y)
print(type(y))

Exit

float
+1
source

For types that transmit the arguments passed in the call (eg int, listetc.), just use the link on this type, and then call it.

>>> x = 1.
>>> y = 2
>>> t = type(x)
>>> t(y)
2.0
>>> tup = (1,2)
>>> lst = [3,4]
>>> t2 = type(tup)
>>> t2(lst)
(3, 4)
+1
source

, type, "float", , __builtins__ ( ):

def get_type_by_name(type_name):
    return getattr(__builtins__, type_name)
the_type = get_type_by_name('float')

:

y = the_type(x)

You can also use evalfor this, but overall eval(sharply) discouraged .

+1
source

You already have good answers, but since programming also concerns playing with materials, here is an alternative:

y.__class__(x)
0
source

Source: https://habr.com/ru/post/1625485/


All Articles