如何根据类型转换对象类型?
How to convert object type based on type?
我有:
x = float(1.0)
y = int(2)
t1 = type(x)
t2 = type(x).__name__
如果我打印 t1
和 t2
我可以看到以下内容:
print t1
>>> <type 'float'>
print t2
>>> float
如何使用t1
或t2
以最少的代码将y
更改为float
类型?
您可以执行以下操作:
x = float(1.0)
y = int(2)
y = type(x)(y)
print(type(y))
输出
float
如果您需要使用类型 name 执行此操作,只需将类型 x
分配给变量并将其用作函数即可:
x = float(1.0)
y = int(2)
t = type(x)
y = t(y)
print(type(y))
输出
float
对于在调用时转换传递参数的类型(如 int
、list
等),只需使用对该类型的引用,然后调用它。
>>> x = 1.
>>> y = 2
>>> t = type(x)
>>> t(y)
2.0
>>> tup = (1,2)
>>> lst = [3,4]
>>> t2 = type(tup)
>>> t2(lst)
(3, 4)
您可以先从表示 type
名称的字符串(例如 "float"
)转换为类型,使用 __builtins__
module (more about here here):
def get_type_by_name(type_name):
return getattr(__builtins__, type_name)
the_type = get_type_by_name('float')
然后,进行转换:
y = the_type(x)
您也可以使用 eval
,但通常 eval
is (harshly) discouraged。
您已经有了很好的答案,但由于编程也是关于玩东西的,这里有一个替代方案:
y.__class__(x)
我有:
x = float(1.0)
y = int(2)
t1 = type(x)
t2 = type(x).__name__
如果我打印 t1
和 t2
我可以看到以下内容:
print t1
>>> <type 'float'>
print t2
>>> float
如何使用t1
或t2
以最少的代码将y
更改为float
类型?
您可以执行以下操作:
x = float(1.0)
y = int(2)
y = type(x)(y)
print(type(y))
输出
float
如果您需要使用类型 name 执行此操作,只需将类型 x
分配给变量并将其用作函数即可:
x = float(1.0)
y = int(2)
t = type(x)
y = t(y)
print(type(y))
输出
float
对于在调用时转换传递参数的类型(如 int
、list
等),只需使用对该类型的引用,然后调用它。
>>> x = 1.
>>> y = 2
>>> t = type(x)
>>> t(y)
2.0
>>> tup = (1,2)
>>> lst = [3,4]
>>> t2 = type(tup)
>>> t2(lst)
(3, 4)
您可以先从表示 type
名称的字符串(例如 "float"
)转换为类型,使用 __builtins__
module (more about here here):
def get_type_by_name(type_name):
return getattr(__builtins__, type_name)
the_type = get_type_by_name('float')
然后,进行转换:
y = the_type(x)
您也可以使用 eval
,但通常 eval
is (harshly) discouraged。
您已经有了很好的答案,但由于编程也是关于玩东西的,这里有一个替代方案:
y.__class__(x)