Python classes and objects (static fields of a class)

Source: Internet
Author: User


Transferred from: http://www.cnblogs.com/Eva-J/p/5044411.html

What is a static field

Before you start, explain what a static field of a class is (I sometimes call it a static variable of a class, and it's all about it.) Most of the following may be referred to as class variables. ):

  

Let's look at the example above, where money is a static field, first of all it's in the Father class, not in __init__. So a small static field, why should I deliberately write a post to it? If you look at it, you will find a small class variable that reflects the whole world of the class.

First, let's explain what is called a static field:

Let's look at the above example, the left and right three graphs, the left is the pure code, the middle is I add to the code of the memory loading process, the right is the execution result. Let's look at the middle diagram here to see the file loading process.

1. Put the class in memory 2. Put the money variable into memory 3. Put the address of the __init__ method into memory

Next we execute a __dict__ method, we look at the right side of the image of the actual execution results, found that this time in memory has been deposited in the money of the variable, it with the execution of the program, as the program ends and disappears, so and the program ' Survival ' field, we call it static field. It is like a global variable that does not belong to any object, we can call it directly using the class, or we can use it when the object uses the method. It is an object-shared variable that exists in the memory of the class.

Methods for calling static fields

  Just now that we know what a static field is, let's take a look at how static fields are used.

The above gives two ways of using, class invocation and object invocation, eh? It looks like you can! Let's change the class variables. Look at this:

We see that when we use the class name. static field names after modifying a class variable, use a class or object to invoke the static field and find that they all have changed. It seems like everything is in our expectation, so the object and class can use the class variable! If you really believe it, it's naïve ... Take a look at the following example:

Look at the above diagram, I was the above example, the yellow box is I add the content, we finally printed out the results of the content, eh? What have we seen? As if the class variables called by the object changed only for the respective object, and did not change the value of the money variable in the class, what about the global variable? How did the phenomenon happen? We don't want to infer:

Look at the above two graphs, the left is the normal logic, when we have a static field in memory of the class, we use the class to call this field, naturally find a static field, when we use the object to call, the object pointer in its own memory to find, found not found, So just use the class pointer maintained in the object to the memory of the class to look for, sure enough to find money, and then the joy of printing out, we have the desire to see the results. When we use the class to invoke this static field for modification, we modify the money field maintained in the class's memory, so it does not affect the above procedure.

Looking at this picture on the right, when we use objects to invoke and change the static fields of a class, they do not have a money field in their own memory, so they go through the class pointers to the class memory, but when they are found, will open up a space in your own memory space to store the modified results for this static field. Therefore, the static fields in the class are not changed at this time, and the money fields in the two objects do not affect each other.

At this point, we add a piece of code on the basis of this and look at the results of the execution, and we find that at this point we use class variables to modify the static variables of the class, to see how the variables in the classes and objects change, and we find that the variables in the object do not change as we expect, which validates our conjecture. Because the money variables are already in the memory of the object, they do not want to Shejinqiuyuan to the class memory to get the variables to show us.

#!/usr/bin/env python#-*-coding:utf-8-*-__author__ = ' Eva_j ' class Father (object):    #静态字段 Money    = 10000    def __init__ (self,name):        #普通字段        self.name = instantiation of the name# class, instantiating two objects separately father_obj1,father_obj2father_obj1 = Father (' obj1 ') Father_obj2 = Father (' obj2 ') #类调用print ' Father.money: ', father.money# object called print ' Father_obj1.money: ', Father_obj1.moneyprint ' Father_obj2.money: ', father_obj2.money# use class invoke to modify Father.money = Father.money + 1000print ' Father.money: ', Father.moneyprint ' Father_obj1.money: ', Father_obj1.moneyprint ' Father_obj2.money: ', Father_ obj2.money# using object invocation Modify Father_obj1.money = Father_obj1.money + 1father_obj2.money = Father_obj2.money + 2print ' Father.money: ', Father.moneyprint ' Father_obj1.money: ', Father_obj1.moneyprint ' Father_obj2.money: ', Father_ Obj2.moneyfather.money = Father.money + 66print ' Father.money: ', Father.moneyprint ' Father_obj1.money: ', Father_ Obj1.moneyprint ' Father_obj2.money: ', Father_obj2.moneydemo Code

However, our variable type transfer dictionary to try, the result is not the same, the code in the following, self-adhesive back to execute it, here will not put your colorful map:

#!/usr/bin/env python#-*-coding:utf-8-*-__author__ = ' Eva_j ' class Father (object): #静态字段 money = {' Money ': 10000} D EF __init__ (self,name): #普通字段 self.name = instantiation of the name# class, instantiating two objects respectively father_obj1,father_obj2father_obj1 = Father ( ' obj1 ') Father_obj2 = Father (' obj2 ') #类调用print ' Father.money: ', father.money[' money '] #对象调用print ' Father_obj1.money: ', father_obj1.money[' money ']print ' Father_obj2.money: ', father_obj2.money[' money '] #使用类调用修改father. "Money[' money ') = father.money[' money ' + 1000print ' Father.money: ', father.money[' money ']print ' Father_obj1.money: ', Father_ obj1.money[' money ']print ' Father_obj2.money: ', father_obj2.money[' money '] #使用对象调用修改father_obj1. "Money[' money ') = father_obj1.money[' money ') + 1father_obj2.money[' money ') = father_obj2.money[' money '] + 2print ' Father.money: ', father.money[' money ']print ' Father_obj1.money: ', father_obj1.money[' money ']print ' Father_obj2.money: ', Father_ obj2.money[' money ']father.money["money" = father.money[' money ') + 66print ' Father.money: ', father. money[' money ']print ' Father_obj1.money: ', father_obj1.money[' money ']print ' Father_obj2.money: ', Father_obj2.money [' Money ']demo Code

Lazy classmate Look here →_→: we just need to remember that when using static variables of the class, you must use the class name to invoke and modify. It will never be shared by classes and objects.

Look at static fields from the perspective of class inheritance

  Just now that we've learned about the storage and invocation of static fields in objects and classes, let's look at static fields from the perspective of class inheritance:

 1 #!/usr/bin/env python 2 #-*-coding:utf-8-*-3 __author__ = ' Eva_j ' 4 class Father (object): 5 6 #静态字段 7 Money = 10000 8 def __init__ (self,name): 9 #普通字段11 self.name = Name12 class Son1 (father): Pass15 Class Son2 (father): Pass18 class Grandson (Son1,son2): Pass21 print ' Father.money: ', father.money23 p Rint ' Son1.money: ', son1.money24 print ' Son2.money: ', son2.money25 print ' Grandson.money: ', grandson.money26 print ' * ' * 2527 Father.money + = 100028 print ' Father.money: ', father.money29 print ' Son1.money: ', son1.money30 print ' Son2.money: ', son2.money31 print ' Grandson.money: ', grandson.money32 print ' * ' *2533 Son1.money + 10034 Son2.money + = 20035 print ' FA Ther.money: ', father.money36 print ' Son1.money: ', son1.money37 print ' Son2.money: ', son2.money38 print ' Grandson.money : ', grandson.money39 print ' * ' *2540 Grandson.money + = 141 print ' Father.money: ', father.money42 print ' Son1.money: ', Son 1.money43 print ' Son2.moNey: ', son2.money44 print ' Grandson.money: ', grandson.money45 print ' * ' *2546 Father.money + = 200047 print ' Father.money : ', father.money48 print ' Son1.money: ', son1.money49 print ' Son2.money: ', son2.money50 print ' Grandson.money: ', GRANDSO N.money51 DemoCode

The result of the above code is this:

The principle is that, when we use the creation class, each base class and derived class will produce their own memory, there are no money variables in the derived class at first, so when they are called, they successfully find the money variable in the parent class through the pointers maintained in the class, and return it to us, but when we use the The name of the derived class. When static field names are modified for static fields in derived classes, they silently place the result of the modification in their own memory space. So in the subsequent call will not go all the way to the parent class to find this variable. In fact, and the above reason is the same as the DA!

  Lazy classmates look here →_→: we just need to remember that when using static variables of a class, if we want the base class and the static fields of each derived class to be shared, it must be called and modified with the base class name. 

Here about the static field of the contents of the class is all finished, a simple static field, unexpectedly inclusive of so many knowledge points, is it worthwhile for us to spend a little time to figure out?

Python classes and objects (static fields of a class)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.