Skip to content

Python 建構子與set與迴圈 #1629

Answered by ATREE01
FakeWood asked this question in Q&A
Discussion options

You must be logged in to vote

你的宣告方式錯誤了
要把set宣告在init內才會是屬於instance的元素,你的寫法會變成屬於class的元素所以不同instance之間會是同一個。

class test:
    def __init__(self, idx):
        self.s = set()
        self.s.add(idx)
        
for i in range(3):
    tmp = test(i)
    print(id(tmp), id(tmp.s), tmp.s)

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by FakeWood
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants