python: class attributes and instance attributes

后端 未结 6 991
滥情空心
滥情空心 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:27

    What happens is the following:

    When you instantiate a new object f1 = Foo(), it does not have any attributes of its own. Whenever you try to access for example f1.a, you get redirected to the class’s Foo.a:

    print f1.__dict__
    {}
    
    print f1.a
    1
    

    However, if you set f1.a = 5, the instance gets a new attribute of that value:

    print f1.__dict__
    {'a': 5}
    

    The class definition is untouched by this, as are any other instances.

    In the second example, you do not reassign anything. With append you are only using that very same list which was defined in the class. Therefore, your instance still refers to that list, as do all other instances.

提交回复
热议问题