Python Class scope & lists

后端 未结 3 1012
死守一世寂寞
死守一世寂寞 2021-02-03 11:27

I\'m still fairly new to Python, and my OO experience comes from Java. So I have some code I\'ve written in Python that\'s acting very unusual to me, given the following code:<

3条回答
  •  不知归路
    2021-02-03 11:51

    I believe the difference is that += is an assignment (just the same as = and +), while append changes an object in-place.

        mylist = []
        mynum = 0
    

    This assigns some class variables, once, at class definition time.

        self.mylist.append("Hey!")
    

    This changes the value MyClass.mylist by appending a string.

        self.mynum += 1
    

    This is the same as self.mynum = self.mynum + 1, i.e., it assigns self.mynum (instance member). Reading from self.mynum falls through to the class member since at that time there is no instance member by that name.

提交回复
热议问题