在 python 中将任何类型的变量应用于另一个变量
Apply any type of a variable to another in 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>
正如 tobias 和 Alex Waygood 在评论中的回答,解决方案非常简单:
type(variable1)(variable2)
或
variable1.__class__(variable2)
我想知道是否可以在 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>
正如 tobias 和 Alex Waygood 在评论中的回答,解决方案非常简单:
type(variable1)(variable2)
或
variable1.__class__(variable2)