Attributes of objects for Python deep learning and attributes for python deep learning

Source: Internet
Author: User

Attributes of objects for Python deep learning and attributes for python deep learning

In Python, everything is an object. Each object can have multiple attributes ). Python attributes have a set of unified management solutions.

_ Dict _ system of the attribute

The attribute of an object may come from its class definition, called class 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 instance, which is called the object attribute ).

The object attributes are stored in the _ dict _ attribute of the object. _ 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.

Copy codeThe Code is as follows:
Class bird (object ):
Feather = True

Class chicken (bird ):
Fly = False
Def _ init _ (self, age ):
Self. age = age

Summer = chicken (2)

Print (bird. _ dict __)
Print (chicken. _ dict __)
Print (summer. _ dict __)

 

The output result is as follows:

Copy codeThe Code 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}

The first behavior is the attributes of the bird class, such as feather. The second behavior is the attributes of the chicken class, such as the fly and _ init _ methods. The third behavior is the property of the summer object, that is, age. Some attributes, such as _ doc __, are not defined by us, but are automatically generated by Python. In addition, the bird class also has a parent class, which is an object class (as defined in bird, 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:
Copy codeThe Code is as follows:
Summer. _ dict _ ['age'] = 3
Print (summer. _ dict _ ['age'])

Summer. age = 5
Print (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 called a property ). 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:

Copy codeThe Code is as follows:
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 are created using the built-in Function property. Property () can load up to four parameters. The first three parameters are functions used to process query features, modify features, and delete features. The last parameter is a feature document, which can be a string that describes the function.

The following example is used for further explanation:

Copy codeThe Code is as follows:
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 the instantly generated attributes. 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:

Copy codeThe Code is as follows:
Class bird (object ):
Feather = True

Class chicken (bird ):
Fly = False
Def _ init _ (self, age ):
Self. age = age
Def _ getattr _ (self, name ):
If name = 'adresult ':
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.

(There is also a special _ getattribute _ method in Python 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) 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.


How to use configuration attributes after a PYThon object

Chinese document? IT can only be Baidu. If online documents do not have Chinese characters, how can IT personnel not learn English.
Ps: dir (object.
 
What are the attributes of python?

What are you talking about?
Python is an object-oriented language. In python, everything is an object.
Objects are variables, classes, and functions in scripts or programs...
Each object has its own attributes, for example, a function has its own shape parameters, logical operations, and so on.
The class concept is similar to the struct in C. It defines a group of objects, has a fixed attribute, and then instantiates the class, that is, inherits all the attributes of the class.
The method is actually a function, the means you use to process objects.

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.