Python goes deep into 03 Object Attributes

Source: Internet
Author: User

Author: vamei Source: http://www.cnblogs.com/vamei welcome reprint, please also keep this statement. Thank you!

 

Python everythingObject), Each object can have multipleAttribute). Python attributes have a set of unified management solutions.

 

_ Dict _ system of the attribute

The object property may come from its class definition, calledClass Attribute). Class attributes may come from the class definition itself or inherit from the class definition. The attribute of an object may also be defined by the object instanceObject attribute).

attributes of an object are stored in __ dict __ attribute. _ Dict _ is a dictionary with the key as the property name and the corresponding value as the property itself. Let's look at the following classes and objects. The chicken class inherits from the bird class, and the summer is an object of the chicken class.

   class   bird (object): feather =< span style =" color: #000000; "> true   class   chicken (BIRD): Fly  =  false   def  __ init __  (self, age): Self. age  =  agesummer  = Chicken (2 )   Print  (bird. __ dict __ )   Print  (chicken. __ dict __ )   Print  (summer. __ dict __)  

 

 

The output result is as follows:

{'_ Dict _': <attribute '_ dict _' of 'bird' objects>, '_ module __': '_ main _', '_ weakref _': <attribute '_ weakref _' of 'bird 'objects>, 'feate': True, '_ Doc _': None}

{'Fly ': false,' _ module _ ':' _ main _ ',' _ Doc _ ': none, '_ init _': <function _ init _ at 0x2b91db476d70>}

{'Age': 2}

First ActBirdSuch as feather. Second actChicken classSuch as fly and _ init. Third ActionSummer object, That is, age. There are some attributes, such_ Doc __Is not defined by us, but automatically generated by python. In addition, the bird class also has a parent class, which is an object class (as defined by our bird class,Class bird (object)). This object class is the parent class of all classes in Python.

As you can see, attributes in Python are defined hierarchically. For example, attributes are divided into four layers: object, bird, chicken, and Summer. When we need to call an attribute, python will traverse it up one by one until the attribute is found. (An attribute may be repeatedly defined at different layers. In the upward process of Python, the attribute that is first encountered is selected, that is, the attribute definition at lower layers ).

When we have a summer object, we can query the attributes of the summer object, chicken class, bird class, and object class respectively to know all the _ dict __, you can find all the attributes that can be called and modified through the object summer. The following two attribute modification methods are equivalent:

Summer._ Dict __['Age'] = 3Print(Summer._ Dict __['Age']) Summer. Age= 5Print(Summer. Age)

 

(In the above case, we already know that the class of the summer object is chicken, and the parent class of the chicken class is bird. If there is only one object without knowing its class and other information, we can use the _ class _ attribute to find the class of the object, then, the _ base _ attribute of the class is called to query the parent class)

 

Features

Different attributes of the same object may have dependencies. When an attribute is modified, we want other attributes of this attribute to change at the same time. In this case, we cannot use _ dict _ to store static attributes. Python provides multiple methods for generating attributes in real time. One of them is calledProperty). A feature is a special attribute. For example, we add a feature adult for the chicken class. When the object age exceeds 1, adult is true; otherwise, false:

 Class  Bird (object): feather = True  Class  Chicken (BIRD): Fly = False  Def   _ Init __  (Self, age): Self. Age =Age  Def  Getadult (Self ):  If Self. age> 1.0: Return  True  Else : Return  False adult = Property (getadult) #  Property is built-in  Summer = Chicken (2 )  Print (Summer. Adult) Summer. Age = 0.5 Print (Summer. Adult)

 

Features use built-in functionsProperty (). Property () can load up to four parameters. The first three parameters are functions for processing.Query features, modify features, and delete features. The last parameter is the featureDocumentIt can be a string to describe the function.

 

The following example is used for further explanation:

 Class  Num (object ):  Def   _ Init __ (Self, value): Self. Value = Value  Def  Getneg (Self ):  Return - Self. Value  Def  Setneg (self, value): Self. Value =- Value  Def  Delneg (Self ):  Print ( "  Value also deleted "  )  Del  Self. Value neg = Property (getneg, setneg, delneg, "  I'm negative  "  ) X = Num (1.1) )  Print  (X. NEG) X. neg =-22 Print  (X. value)  Print (Num. neg. _ Doc __ )  Del X. neg

 

The preceding num is a number, while neg is a feature used to indicate negative numbers. When a number is determined, its negative number is always determined. When we modify a negative number, its own value should also change. These two points are implemented by getneg and setneg. Delneg indicates that if you delete the feature neg, you should delete the attribute value. The last parameter ("I'm negative") of property () is a description of the feature negative.

 

Use special method _ getattr __

We can use_ Getattr _ (self, name)To query generated properties. When we query an attribute, if the attribute cannot be found through the _ dict _ method, python will call the _ getattr _ method of the object to generate the attribute instantly. For example:

 Class  Bird (object): feather = True  Class  Chicken (BIRD): Fly = False  Def   _ Init __  (Self, age): Self. Age = Age  Def   _ Getattr __  (Self, name ):  If Name = '  Adult  ' :  If Self. age> 1.0: Return  True  Else : Return  False  Else : Raise  Attributeerror (name) Summer = Chicken (2 )  Print  (Summer. Adult) Summer. Age = 0.5 Print (Summer. Adult)  Print (Summer. Male)

 

 

Each feature requires its own processing function, and _ getattr _ can put all the instantly generated attributes in the same function for processing. _ Getattr _ different attributes can be processed according to the function name difference. For example, raise attributeerror occurs when we query the attribute name male.

(Python also has_ Getattribute __Special method used to query Any attribute. _ Getattr _ can only be used to query attributes not in the _ dict _ system)

_ Setattr _ (self, name, value)And_ Delattr _ (self, name)It can be used to modify and delete attributes. They have a wider application scope and can be used for any attribute.

 

Other methods for generating attributes instantly

You can also use other methods to generate attributes in real time. For example, the descriptor class is actually the bottom layer of the property () function, and the property () actually creates an object of this class ). For more information, see.

 

Summary

_ Dict _ Hierarchical Storage attribute. The _ dict _ of each layer only stores the new attributes of this layer. Subclass does not need to store attributes in the parent class repeatedly.

Generating attributes instantly is a concept worth understanding. In Python development, you may use this method to manage object attributes more rationally.

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.