Class and object Methods
We have discussed the functions of classes and objects. Now let's take a look at its data section. In fact, they are onlyNamespace BindThat is, these names are valid only on the premise of these classes and objects.
There are two typesDomain-- Class variables and object variables, which are based on the class or objectYesThis variable is differentiated.
Class variablesShared by all objects (instances) of a class. Only one class variable is copied, so when an object changes the class variable, this change will be reflected on all other instances.
Object VariablesIt is owned by each object/instance of the class. Therefore, each object has its own copy of this domain, that is, they are not shared. In different instances of the same class, although the object variables have the same name, however, they are unrelated. This is easy to understand through an example.
Use the class and object variable # filename: objvar. py
Class person:
Population = 0
Def _ init _ (self, name ):
Self. Name = Name
Print ("Initializing % s") % self. Name
Person. Population + = 1
Def sayhi (Self ):
Print ("Hi, my name is % s") % self. Name
Print ('there are % d people in the world' % person. Population)
Def _ del _ (Self ):
Print "% s says goodbye" % self. Name
Person. Population-= 1
If (person. Population = 0 ):
Print 'no one in the world'
Else:
Print "there are still % d people left" % person. Population
A1 = person ("Shanshan ");
A1.sayhi ()
A2 = person ("siliang ")
A2.sayhi ()
Del A1
Del A2