python - 在python中将任何类型的变量应用于另一个变量
问题描述
我想知道是否可以在 Python 中从变量中“提取”构造函数类型(元类?),以便使用它以编程方式将另一个变量类型转换为相同类型,而不必有任何“先验期望”关于我们可以遇到的类型。
如果这样更有意义,那么实现将是以下领域的东西:
def copyType(destination_var,source_var):
try:
type_class = way_to_get_the_type_metaclass(source_var)
return typeclass(destination_var)
# as if we did str(destination_var) or int(destination_var) or
# any other class, but without having to have expectation and being forced to check
# if isinstance(var, str) : elif isinstance(var,int) : .... and so on
except :
raise TypeError
variable1 = "157"
variable2 = 34
print(type(variable1))
print(type(variable2))
variable2 = copyType(variable2 ,variable1)
print(type(variable2))
>>> Out : <str>
<int>
<str>
解决方案
正如托拜厄斯和亚历克斯韦古德在评论中回答的那样,解决方案很简单:
type(variable1)(variable2)
或者
variable1.__class__(variable2)
推荐阅读
- c# - 仅将包含 3 个文件的特定文件夹复制到新文件夹
- angular - 在 p-dialog 上打开花式框时关闭 PRIMENG 的 p-dialog
- rust - 如何在 const 结构中初始化 BTreeMap?
- r - 如何计算列表矩阵列的标准偏差
- c# - Azure AD 应用程序身份验证成功地对同一租户中的所有应用程序进行身份验证,而无需委派/白名单权限
- php - basename 更改非 ascii 字符
- mysql - Mysql不会插入数据库
- c# - 我想通过使用 EF 更改另一个表来更新表
- unity3d - Unity 制作可选择的 3D 地球
- python - 为什么没有出现下一个直方图?