Python 清空变量而不销毁它

Python 清空变量而不销毁它,python,variables,Python,Variables,我有一段代码: a = "aa" b = 1 c = { "b":2 } d = [3,"c"] e = (4,5) letters = [a, b, c, d, e] 我想用它做点什么,这样可以清空它们。不会失去他们的类型 大概是这样的: >>EmptyVars(letters) ['',0,{},[],()] 有什么提示吗?请执行以下操作: def EmptyVar(lst): return [type(i)() for i in lst] type() 演示: 类

我有一段代码:

a = "aa"
b = 1
c = { "b":2 }
d = [3,"c"]
e = (4,5)
letters = [a, b, c, d, e]
我想用它做点什么,这样可以清空它们。不会失去他们的类型

大概是这样的:

>>EmptyVars(letters)
['',0,{},[],()]
有什么提示吗?

请执行以下操作:

def EmptyVar(lst):
    return [type(i)() for i in lst]
type()

演示:


类似的方式,只需将
类型(i)(
替换为
i.\uuu class\uuu()


我们可以借助type()函数来实现这一点,该函数通常用于显示python中任何对象或变量的类型。 以下是解决方案:

a = "aa"
b = 1
c = {"b" : 2}
d = [3, "c"]
e = (4,5)
letters = [a,b,c,d,e]
print([type(i)() for i in letters])

这很聪明..我喜欢它可能值得注意的是,“清空”它们与创建默认类型的新实例并不完全相同。。。因此,其他行为,例如
.clear()
对于
MutableMapping
以及类似的
MutableSet
MutableSequence
兼容类型,可能在其他情况下也适用。@kame:
type(i)
返回类型对象
int
对于整数,
list
对于列表对象等。类型对象是可调用的,因此
Type(i)(
调用类型对象,该类型对象是相同类型的空新对象。因此Type(i)()类似于函数?是
type()
返回一个可调用的对象,就像函数也可以被调用一样。您也可以将结果存储在变量中:
foo=type(0)
将结果存储在
foo
中。然后,您可以调用
foo()
来生成一个新的整数
0
。运行
EmptyVars
后,您是否希望
d
[]
a = "aa"
b = 1
c = {"b": 2}
d = [3, "c"]
e = (4, 5)

letters = [a, b, c, d, e]


def empty_var(lst):
    return [i.__class__() for i in lst]


print(empty_var(letters))

['', 0, {}, [], ()]
a = "aa"
b = 1
c = {"b" : 2}
d = [3, "c"]
e = (4,5)
letters = [a,b,c,d,e]
print([type(i)() for i in letters])