Python Variables of Class or Instance
What they are?
In Python class, there are two kinds of variables: class variables and instance variables.
Kinds | Belong | Declear | Value |
---|---|---|---|
Class | Class | Class Block | Share |
Instance | Instance | Inside functions | Unique |
For example, we have class variables a
and b
, and instance variables c
.
1 | class Example: |
Difference
Initialization
From the above example, we can see that the class variables are pre-set by definition, but the instance variables should initialize by the instance initialization.
Calling
For class variables, we could call it by any instance of the class, or just use the class name. For instance variables, we can only call it by the corresponding instance. For instance:
1 | e1 = Example(1) |
Modification
Since class variables belong to the class itself, all instances of the same class will share the same values of those variables. Edit the value of class variables though one instance will be reflected when calling the same variable by other instances or classes.
Following the above instance, we have:
1 | print(Example.a) # a |
Priority
Similar to the local variables and global variables, the priority of the instance variable is higher than the class variable. That means if one instance and class variable has the same name with different values, Python will print the value of the instance first when calling by instance. For example, we define the class Example2
:
1 | class Example2: |
Conclusion
In object-oriented programming, Python defines the class-level variables as class variables and sees the object level as instance variables. Initialization, calling, modification, and priority are four different points they have. Correct usage could help reduce the repeat and code smartly.