首页 > 解决方案 > 在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>

标签: pythontypescasting

解决方案


正如托拜厄斯和亚历克斯韦古德在评论中回答的那样,解决方案很简单:

type(variable1)(variable2)

或者

variable1.__class__(variable2)

推荐阅读