python: class attributes and instance attributes

后端 未结 6 987
滥情空心
滥情空心 2020-12-01 19:54

I\'m new to python and learned that class attributes are like static data members in C++. However, I got confused after trying the following code:

>>&g         


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-01 20:16

    You're not doing the same thing in your second example. In you first example, you are assigning f1.a a new value:

    f1.a = 5
    

    In your second example, you are simply extending a list:

    f1.a.append(5)
    

    This doesn't change what f1.a is pointing to. If you were instead to do this:

    f1.a = [5]
    

    You would find that this behaves the same as your first example.

    But consider this example:

    >>> f1=Foo()
    >>> f2=Foo()
    >>> Foo.a = 5
    >>> f1.a
    5
    >>> f2.a
    5
    

    In this example, we're actually changing the value of the class attribute, and the change is visible in all instances of the class. When you type:

    f1.a = 5
    

    You're overriding the class attribute with an instance attribute.

提交回复
热议问题