Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何根据类型转换对象类型?_Python_Types_Instance - Fatal编程技术网

Python 如何根据类型转换对象类型?

Python 如何根据类型转换对象类型?,python,types,instance,Python,Types,Instance,我有: 如果我打印t1和t2我可以看到以下内容: x = float(1.0) y = int(2) t1 = type(x) t2 = type(x).__name__ print t1 >>> <type 'float'> print t2 >>> float 打印t1 >>> 打印t2 >>>浮动 如何使用t1或t2以最少的代码量将y更改为类型float x = float(1.0) y = int(2) t1 = type(x

我有:

如果我打印
t1
t2
我可以看到以下内容:

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

t1 = type(x)
t2 = type(x).__name__
print t1
>>> <type 'float'>

print t2
>>> float
打印t1
>>> 
打印t2
>>>浮动

如何使用
t1
t2
以最少的代码量将
y
更改为类型
float

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

t1 = type(x)
t2 = type(x).__name__
print t1
>>> <type 'float'>

print t2
>>> float
输出

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

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

t = type(x)
y = t(y)
print(type(y))
如果需要使用类型名称执行此操作,只需将
x
的类型指定给变量,并将其用作函数:

float
输出

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

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

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

对于调用时强制转换传递参数的类型(如
int
list
等),只需使用对该类型的引用,然后调用它

float

您可以首先使用模块将表示
类型
名称的字符串(如
“float”
)转换为类型(此处有更多信息):

然后,进行转换:

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

您也可以使用
eval
,但一般来说。

您已经有了很好的答案,但由于编程也是关于玩东西的,这里有一个替代方案:

y = the_type(x)

您是否需要使用类型名来执行此操作,或者只使用类型本身就可以了?正如下面的答案所示,后一种情况更为直截了当。是的,我需要使用类型名称来完成此操作。实际上,不,我不需要名称。我的错误。我正在编辑问题并接受最佳答案。您的答案中使用的类型名称在哪里?没有一个变量是stringsI(OP)出错的。我不需要类型名。也许你的意思是
y=x.\uu类\uuu(y)