How many memory copies do object variables in Python have?

This question already has an answer here:

  • Are static class variables possible? 16 answers

  • In python, anything declared at the class scope is effectively global. When you look up that attribute on an instance, python doesn't find it, so it then looks on the class (then it continues looking on the base classes all the way up the method resolution order). So, in your case, x.list is the exact same thing as A.list because there is no instance attribute list attached to x . Similary, y.list is the same as A.list so x.list and y.list refer to the same underlying list. (Phew!)

    As I understand it, this is at least similar to Java's static (though I'm not fluent enough in Java to say exactly how similar).

    The typical way to disassociate an attribute from the class is to bind that attribute to an instance (usually in __init__ ):

    class A(object):
        def __init__(self):
            self.list = []
    

    In the above example, self is the instance and it gets passed (implicitly) to any 'normal' method (including "magic" methods like __init__ ).

    Now if you do your experiment again, you'll see that x.list takes the value of [1, 3] and y.list is now [2, 4] .


    Now the test. What happens if you do your experiment on this class?

    class A(object):
        list = []
        def __init__(self):
            self.list = []
    

    Answer: x.list = [1, 3] and y.list = [2, 4] . The reason is because when python does x.list , it looks on the instance first (before looking at the class). Since an attribute with the name list is found on the instance, that is the one that is used.

    链接地址: http://www.djcxy.com/p/78774.html

    上一篇: 类变量是否可变?

    下一篇: Python中的对象变量有多少内存副本?