search

Home  >  Q&A  >  body text

python中在class中使用set()的问题

我写了如下的一段代码:
所有的代码都是在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(),这个问题又该如何解决呢?

巴扎黑巴扎黑2890 days ago412

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 18:00:51

    Set.union generates a new set without changing the current object.

    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)

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 18:00:51

    The reason is as @exudong said.

    It will be easier to change it to the following:

    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)

    But I am still curious, why not just put it at the beginning self.data 設定成 {1, 2, 3}?

    reply
    0
  • Cancelreply