# Python # Data Model

Source: Internet
Author: User

Today, let's talk aboutData ModelOf course, you can write beautiful Python without learning about these things.CodeBut "knowing what it is" is my style of work. I am not familiar with some Python mechanisms, and I am very upset. Combined with the python Doc and an article, I almost understood the python philosophy.

I think it is necessary to take out some important statements in the python documentation.

Objects are Python's own action for data. All data in a python program is represented by objects or by relations between objects.
Every object has an identity, a type and a value.

Why do I want to emphasize the object here? Some objects think that there are some attributes (functions or variables are all attributes) associated with them. You can operate on an object, it is actually dealing with these attributes.

Here, I focus on the classes in Python To figure out how classes in Python complete their functions.
A class has a namespace implemented by a dictionary object. Class Attribute references are translated to lookups in this dictionary.

This sentence is very important.Class has its own namespace (namespace)And the implementation of this namespace is essentiallyDictionary. In other words, your operations on a class are actually performed on this "special" dictionary.Zone-specific instances and ClassesIn python, the class instance also has a dictionary to record the attributes of the instance.

View plaincopy to clipboardprint?
    1. ClassT (object ):
    2. Age =21
    3. T = T ()
    4. T. Name ="Ilovebaiyang"
    5. Print "Dir (t ):", Dir (t)
    6. Print "Dir (t ):", Dir (t)

The printed result is:

View plaincopy to clipboardprint?
  1. Dir (t ):['_ Class __','_ Delattr __','_ Dict __','_ Doc __','_ Format __','_ Getattribute __','_ Hash __','_ Init __','_ Module __','_ New __','_ Reduce __','_ Performance_ex __','_ Repr __','_ Setattr __','_ Sizeof __','_ STR __','_ Subclasshook __','_ Weakref __','Age']
  2. Dir (t): [ '_ class _' , '_ delattr _' , '_ dict _' , '_ Doc _' , '_ format _' , '_ getattribute _' , '_ Hash _' , '_ init _' , '_ module _' , '_ new _' , '_ reduce _' , '_ performance_ex _' , '_ repr _' , '_ setattr _' , '_ sizeof _' , '_ STR _' , '_ subclasshook _' , '_ weakref _' , 'age' , 'name' ]

Some of these attributes are inherited from the object, such as _ Doc __, _ setattr __,__ dict _, and so on. It is worth noting that custom attributes are defined, age and name exist in instance t of class T and instance t respectively. Why does the age attribute appear in Dir (t, the reason is that it is copied from its class, And if we print their ID, they actually have the same ID. Here, we have a question: is the dictionary of the namespace mentioned above the dictionary generated by the Dir () function? It looks like, because it does record all attributes of the object, this is actually an error, and we will go back to the Dir function. Its role is to list all attributes of the current object, including the parent class. In fact, the namespace mentioned above is a member of _ dict _, and all the attributes corresponding to this object are put in this dictionary.

Let's print it out.

View plaincopy to clipboardprint?
    1. T. _ dict __:{'_ Dict __':,'_ Module __':'_ Main __','_ Weakref __':,'Age':21,'_ Doc __':None}
    2. T. _ dict __:{'Name':'Ilovedomainyang'}

This will be the same as we think. The name attribute only exists in the instance.
Next we will look up the attributes:
If we want to print T. Age, how to search

    • 1. First find the _ dict __of the instance. If yes, return. Otherwise, proceed to step 2.
    • 2. Find the _ dict __of the class. If any, continue to search for the parent class of the class until the base class does not exist. If not, an exception is thrown.

Of course, in fact, the search in Python has done many other things, especially some implicit calls. If we rewrite these implicit calls, we can write data that fits our needs.
See the following example:

View plaincopy to clipboardprint?
  1. ClassT (object ):
  2. Def_ Setattr __(Self, Name, value ):
  3. Print "_ Setattr _ called"
  4. Object. _ setattr __(Self, Name, value)
  5. Def_ Getattr __(Self, Name ):
  6. Print "_ Getattr _ called"
  7. Def_ Getattribute __(Self, Name ):
  8. Print "_ Getattribute _ called"
  9. ReturnObject. _ getattribute __(Self, Name)
  10. T = T ()
  11. T. Name ="Yang"
  12. Print "T", T. Name
  13. T. Yang

Result:

    1. _ Setattr _ called
    2. T _ getattribute _ called
    3. Yang
    4. _ Getattribute _ called
    5. _ Getattr _ called

Analyze the above results when T. when name is executed, the _ setattr _ function is called first. When print "T", T. the _ getattribute _ function is called. When T. the _ getattr _ function is called when the variable is Yang. Because t does not have the variable Yang attribute, the function is called.

As a matter of fact, we will understand that when we operate the namespace dictionary, we will call the corresponding functions implicitly, which can be used for data verification.
To sum up, when operating the instance attributes, we need to pay attention to the functions:
Object. _ setattr _ (self, name, value)
Object. _ getattr _ (self, name)
Object. _ delattr _ (self, name)
Object. _ getattribute _ (self, name)

When you access the attributes of any object, the _ getattribute _ method is called implicitly. For example, you call T. _ dict __, you actually executed T. _ getattribute _ ("_ dict _") function.

The magical python uses the dictionary so flexibly that it can be seen how important the dictionary is in Python.

Here, we may think about how to call these functions implicitly. Right, we can directly operate the _ dict _ of a class or class instance __. Take a look at the following example:

View plaincopy to clipboardprint?
  1. ClassT (object ):
  2. Age =21
  3. Def_ Setattr __(Self, Name, value ):
  4. Print "_ Setattr _ called"
  5. Object. _ setattr __(Self, Name, value)
  6. Def_ Getattr __(Self, Name ):
  7. Print "_ Getattr _ called"
  8. Def_ Getattribute __(Self, Name ):
  9. Print "_ Getattribute _ called"
  10. ReturnObject. _ getattribute __(Self, Name)
  11. T = T ()
  12. T. _ dict __["Name"] ="Yang"
  13. Print "T. _ dict __:", T. _ dict __["Name"]
  14. Print "T. Age :", T. Age
  15. Print "T. _ dict _ ['age']:", T. _ dict __["Age"]

Result

View plaincopy to clipboardprint?
  1. _ Getattribute _ called
  2. T. _ dict __: _ getattribute _ called
  3. Yang
  4. T. Age: _ getattribute _ called
  5. 21
  6. T. _ dict __['Age']: _ Getattribute _ called
  7. Traceback (most recent call last ):
  8. File"C: \ Users \ Administrator \ Desktop \ lab \ sogouw \ freq \ test. py", Line18,In
  9. Print "T. _ dict _ ['age']:", T. _ dict __["Age"]
  10. Keyerror:'Age'

Let's analyze:
1. T _ dict _ ["name"] = "Zhangyang", where the _ getattribute _ function is called, because _ dict _ is also an attribute, therefore, it must be executed, but you will find that _ setattr _ is not executed at this time, achieving the desired effect;
2. Print "T. Age:", T. Age
Print "T. _ dict _ ['age']: ", T. _ dict _ ["Age"] This is the focus. The second statement throws a keyerror and once again proves that age only exists in the namespace of the class.

Finally, we will compare it with the descriptor in Python:
I will not elaborate on this article.
The main point is that the corresponding function of descriptor is
Object. _ GET _ (self, instance, owner)
Object. _ SET _ (self, instance, value)
Object. _ Delete _ (self, instance)
We can see that the word ATTR is missing, and we thought we had to differentiate them. Descriptor is an operation on the instance of the class, and the built-in Function Property () is implemented in this way. After reading this article, do you know more about the working mechanism of python?
Okay. I 'd like to ask you a few questions here. You can search for answers online.

    • How to Create immutable data is provided in my previous article.
    • How to create data in singleton Mode

If you understand the aboveArticleYou will understand that no matter what data you want to write, you just need to rewrite some internal functions in Python.

 

----------------- Create high-quality articles. pay more attention to the wine ---------------

To create high-quality articles, pleaseRecommendationOne, right .... Thank you. I will write more good articles.

Sina Weibo: http://weibo.com/baiyang26

The wine ghost official blog: http://www.ibaiyang.org [recommended to use Google Reader subscription]

Pour wine into the official Douban: http://www.douban.com/people/baiyang26/

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.