Python Class scope & lists

后端 未结 3 1011
死守一世寂寞
死守一世寂寞 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 12:08

    tlayton's answer is part of the story, but it doesn't explain everything.

    Add a

    print MyClass.mynum
    

    to become even more confused :). It will print '0'. Why? Because the line

    self.mynum += 1
    

    creates an instance variable and subsequently increases it. It doesn't increase the class variable.

    The story of the mylist is different.

    self.mylist.append("Hey!")
    

    will not create a list. It expects a variable with an 'append' function to exist. Since the instance doesn't have such a variable, it ends up referring the one from the class, which does exist, since you initialized it. Just like in Java, an instance can 'implicitly' reference a class variable. A warning like 'Class fields should be referenced by the class, not by an instance' (or something like that; it's been a while since I saw it in Java) would be in order. Add a line

    print MyClass.mylist
    

    to verify this answer :).

    In short: you are initializing class variables and updating instance variables. Instances can reference class variables, but some 'update' statements will automagically create the instance variables for you.

提交回复
热议问题