Python Class scope & lists

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

    What you are doing here is not just creating a class variable. In Python, variables defined in the class body result in both a class variable ("MyClass.mylist") and in an instance variable ("a.mylist"). These are separate variables, not just different names for a single variable.

    However, when a variable is initialized in this way, the initial value is only evaluated once and passed around to each instance's variables. This means that, in your code, the mylist variable of each instance of MyClass are referring to a single list object.

    The difference between a list and a number in this case is that, like in Java, primitive values such as numbers are copied when passed from one variable to another. This results in the behavior you see; even though the variable initialization is only evaluated once, the 0 is copied when it is passed to each instance's variable. As an object, though, the list does no such thing, so your append() calls are all coming from the same list. Try this instead:

    class MyClass():
        def __init__(self):
            self.mylist = ["Hey"]
            self.mynum = 1
    

    This will cause the value to be evaluated separately each time an instance is created. Very much unlike Java, you don't need the class-body declarations to accompany this snippet; the assignments in the __init__() serve as all the declaration that is needed.

提交回复
热议问题