[英]Initialize variable depending on another variables type
In Python 2.7 I want to intialize a variables type depending on another variable.在 Python 2.7 中,我想根据另一个变量初始化变量类型。
For example I want to do something like:例如,我想做类似的事情:
var_1 = type(var_2)
Is there a simple/fast way to do that?有没有简单/快速的方法来做到这一点?
Just create another instance只需创建另一个实例
var_1 = type(var_2)()
Note that if you're not sure whether the object has a non-default constructor, you cannot rely on the above, but you can use copy
or deepcopy
(you get a "non-empty" object.请注意,如果您不确定该对象是否具有非默认构造函数,则不能依赖于上述内容,但您可以使用
copy
或deepcopy
(您会得到一个“非空”对象。
import copy
var_1 = copy.copy(var_2) # or copy.deepcopy
You could use both combined with the latter as a fallback mechanism您可以将两者结合使用作为后备机制
Note: deepcopy
will ensure that your second object is completely independent from the first (If there are lists of lists, for instance)注意:
deepcopy
将确保您的第二个对象完全独立于第一个(例如,如果有列表列表)
a = 1 # a is an int
a_type = type(a) # a_type now contains the int-type
b = '1' # '1' is a string
c = a_type(b) # c is now an int with the value 1
So you can get the type of a variable using type()
.因此,您可以使用
type()
获取变量的type()
。 You can then store this type in a variable and you can then use that variable just like you would use int(b)
, str(b)
, float(b)
etc.然后您可以将此类型存储在一个变量中,然后您可以像使用
int(b)
、 str(b)
、 float(b)
等一样使用该变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.