Compound assignment to Python class and instance variables

前端 未结 5 1961
天涯浪人
天涯浪人 2020-12-10 18:04

I\'ve been trying to understand Python\'s handling of class and instance variables. In particular, I found this answer quite helpful. Basically it says that if you declare a

5条回答
  •  执笔经年
    2020-12-10 18:45

    In the following code, num is a class member.

    class Foo:
        num = 0
    

    A C++ equivalent would be something like

    struct Foo {
      static int num;
    };
    
    int Foo::num = 1;
    

    class Foo:
        def __init__(self):
            self.num = 0
    

    self.num is an instance member (self being an instance of Foo).

    In C++, it would be something like

    struct Foo {
      int num;
    };
    

    I believe that Python allows you to have a class member and an instance member sharing the same name (C++ doesn't). So when you do bar = Foo(), bar is an instance of Foo, so with bar.num += 1, you increment the instance member.

提交回复
热议问题