Maison > Questions et réponses > le corps du texte
我写了如下的一段代码:
所有的代码都是在Python3.4下编写的
class test_set:
def __init__(self):
self.data = set()
def start(self):
myset = set([1,2,3])
self.data.union(myset)
t1 = test_set()
t1.start()
print(t1.data)
结果输出的是:set()
我想知道为什么这个t1.data不是set{1,2,3},却是没有数据呢?
但是我如果将data修改为list,代码如下:
class test_set:
def __init__(self):
self.data = []
def start(self):
myset = [1,2,3]
self.data.extend(myset)
t1 = test_set()
t1.start()
print(t1.data)
程序输出的是:[1,2,3]
想知道在class中使用set(),为什么会出现这种现象。如果要使用set(),这个问题又该如何解决呢?
伊谢尔伦2017-04-17 18:00:51
Set.union génère un nouvel ensemble sans changer l'objet actuel.
class test_set:
def __init__(self):
self.data = set()
def start(self):
myset = set([1,2,3])
self.data = self.data.union(myset)
t1 = test_set()
t1.start()
print(t1.data)
高洛峰2017-04-17 18:00:51
La raison est comme @exudong l'a dit.
Il sera plus facile de le changer comme suit :
class test_set:
def __init__(self):
self.data = set()
def start(self):
self.data = self.data.union({1,2,3})
t1 = test_set()
t1.start()
print(t1.data)
Mais je suis toujours curieux, pourquoi ne pas simplement régler self.data
sur {1, 2, 3}
?