转自:http://www.cnblogs.com/Eva-J/p/5044411.html
什么是静态字段
在我们开始之前,上图解释了什么是类的静态字段(我有时将其称为类的静态变量,但仅此而已。后一种情况中的大多数可以简称为类变量。):
[En]
Before we begin, the figure above explains what a static field of a class is (I sometimes call it a static variable of a class, but it's all about it. Most of the latter cases may be referred to as class variables for short. ):
我们看上面的例子,这里的money就是静态字段,首先看它的位置,是在father类中,而不是在__init__中。那么一个小小的静态字段,我为什么要特意写一篇番外给它呢?耐着性子看下去,你就会发现一个小小的类变量,却折射出了整个类的世界。
首先我们先来解释一下什么叫做静态字段:
让我们来看一下上面的例子,左边是三张图片,左边是纯代码,中间是我添加到代码中的内存加载过程,右边是执行结果。让我们首先看一下中间的图片,看看加载该文件的过程。
[En]
Let's take a look at the example above, three pictures on the left, the pure code on the left, the memory loading process I added to the code in the middle, and the execution result on the right. Let's first look at the middle picture here to see the process of loading this file.
1.将类存入了内存 2.将money变量放入了内存 3.将__init__方法的地址放入了内存
接下来我们执行了一个__dict__方法,我们看右边图中现实的执行结果,发现这个时候内存中已经存入了money这个变量,它随着这个程序 的执行产生,随着程序的结束而消失,这样和程序'共存亡'的字段,我们就叫它静态字段。它就像是一个全局变量,不属于任何一个对象,我们可以直接使用类来 调用,也可以在对象使用方法的时候使用它。它是对象共享的变量,存在类的内存里。