I want to learn how to create an instance in one of the compiling classes of Python and how to learn python.

Source: Internet
Author: User

I want to learn how to create an instance in one of the compiling classes of Python and how to learn python.

Note: I have explained this part of the class by referring to the book "Learning Python.

Create class

The method for creating a class is simple as follows:
Copy codeThe Code is as follows:
Class Person:

Note that the class name generally starts with an upper-case letter. This is a convention. Of course, if you deliberately do not follow this practice, it will not be difficult, but it will cause difficulties for others to read and read. Since everyone is right-leaning, you don't have to go to bed in the middle of the road.

Next, we usually need to write constructors. before writing this function, Let's explain what constructor is.
Copy codeThe Code is as follows:
Class Person:
Def _ init _ (self, name, lang, website ):
Self. name = name
Self. lang = lang
Self. website = website

In the above class, a function named :__ init _ () is first presented. Note that this function starts with two underscores and then init, end with two underscores. This is a function, just like the function we have learned before. However, this function is a bit strange, and its name is "_" to start and end.

For details, refer to the following description: A class is an object type, which is the same as the type of values, strings, lists, and so on. For example, if the class name is "Person", we will try to create an object type. This type is called "Person", just as there is a list object type.

When building the Person class, the first thing to do is to initialize this type, that is, to describe the basic structure of this type. Once this type of object is called, the first thing is to run the basic structure of this type, that is, the basic structure of the class Person. For example, each of us has an object type (corresponding to the class) such as "person" in our minds. Once Zhang San (Zhang San is a specific person ), we first run the basic structure of the "person" Class: one nose and two eyes, and one mouth under the nose. If Michael fits this basic organization, we will not be surprised (no error is reported). If Michael does not conform to this basic structure (for example, three eyes), we will be surprised (an error is reported ).

Because classes are constructed by ourselves, the basic structure is also manually constructed by ourselves. In the class, the basic structure is written in the _ init _ () function. Therefore, this function is called a constructor and is responsible for class initialization.

Return to the Person class. If the code above has been written, will it run as _ init? No! At this time, Zhang San is not seen yet. It must be seen before Zhang San can run. The so-called seeing Zhang San, seeing Zhang San such a specific real person, this action has a term in python called Instantiation. Run the _ init _ () function immediately after the class Person is instantiated.
Copy codeThe Code is as follows:
#! /Usr/bin/env python
# Coding: UTF-8

Class Person:
Def _ init _ (self, name, lang, website ):
Self. name = name
Self. lang = lang
Self. website = website

Info = Person ("qiwsir", "python", "qiwsir. github. io") # instantiate Person
Print "info. name =", info. name
Print "info. lang =", info. lang
Print "info. website =", info. website

# Running result of the code above:

Info. name = qiwsir
Info. lang = python
Info. website = qiwsir. github. io

In the above Code, the Person class created by the constructor declares the basic structure of this class: name, lang, website.

Note: info = Person ("qiwsir", "python", "qiwsir. github. io") is used to instantiate the class Person. That is, an object is created in the memory. The object type is Person. What does the Person type look like? It is constructed by _ init. During instantiation, you must pass in specific data through parameters: name = "qiwsir", lang = "python", website = "qiwsir. github. io ". In this way, an object exists in the memory. The object type is Person, and then the reference relationship is established with the variable info through the value assignment statement. Remember the reference relationships between variables and objects that have previously been described.

Is it a bit dizzy? Classes and instances. These two concepts will be followed by subsequent learning and will be met in many OOP models. In order to make the audience uncomfortable, we will compare them here (NOTE: For the comparison content, refer to the book Learning Python)

Class and instance
• "Classes provide default behaviors and are the factory of instances". I think this sentence is very classic. It breaks through the relationship between classes and instances. Let's look at the code above and try it out. Is it true? The so-called factory means that many specific products can be made using the same model. Class is the model, and the instance is the specific product. Therefore, the instance is the actual object processed by the program.
• A class is composed of some statements, but the instance is generated by calling the class. Each time a class is called, a new instance of the class is obtained.
• For class: class Person, class is an executable statement. If executed, a class object is obtained and the class object is assigned to the object name (such as Person ).
 
Maybe the above comparison is not enough for the viewer to understand the class and the instance. It doesn't matter. Continue to learn and eliminate doubts in the forward.

Role of self

You may have noticed that the first parameter in the constructor is self, but this parameter does not seem to happen during instantiation. So what does self do?

Self is a magic parameter.

In the process of Person instantiation, the data "qiwsir", "python", "qiwsir. github. io "has been saved to the memory through the parameters of the constructor (_ init _ (), and the data forms an object with the appearance of Person, reference relationship between this object and the variable info. This process can also be said to attach the data to an instance. In this way, a data can be called anywhere in the program in the form of: object. attribute. For example, the above program obtains the data "qiwsir" with info. name. This call method is often used in classes and instances. The class or instance attribute is called after.

This is in the program and outside the class. What if I want to use the imported data somewhere in the class?

As the study goes deeper, the reader will find that in the class, we will write many functions with different functions. These functions have another name in the class: method. If you want to use the data passed in through the parameters in the constructor of the class in each method, you need to save the data in the class for a long time and call the data at any time. To solve this problem, all incoming data in the class is assigned to a variable. Generally, the name of this variable is self. Note that this is a habit and consensus. Therefore, you should not take another name.

The first parameter self in the constructor is used to receive all the data passed in during the instantiation process. The data is imported by the parameters following the constructor. Obviously, self should be an instance (accurately speaking, an application instance) because it corresponds to specific data.

If you add two sentences to the above class to see the effect:
Copy codeThe Code is as follows:
#! /Usr/bin/env python
# Coding: UTF-8

Class Person:
Def _ init _ (self, name, lang, website ):
Self. name = name
Self. lang = lang
Self. website = website

Print self # print and see what results
Print type (self)

# Running result
<__ Main _. Person instance at 0xb74a45cc>
<Type 'instance'>

The reasoning is confirmed. Self is an instance (the variable referenced by the instance ).

The instance self has the same attributes as the Instance Object referenced by the info mentioned earlier. Then, define the data corresponding to its attributes. In the above Code: self. name = name indicates an attribute of the self instance. The name of this attribute is also called name. The data of this attribute is equal to the data imported by the constructor parameter name. Note: self. the name in name has nothing to do with the parameter name of the constructor. The two are the same, but it is a coincidence (often coincidence), or the code writer is lazy, I don't want to get another name. Of course, you can also write self. xxxooo = name.

In fact, it may be simpler to understand from the perspective of effect, that is, the instance info of the class corresponds to self, and info imports all data of the Instance attribute through self.

Of course, the property data of self does not have to be passed in by parameters. You can also set it in the constructor. For example:
Copy codeThe Code is as follows:
#! /Usr/bin/env python
# Coding: UTF-8

Class Person:
Def _ init _ (self, name, lang, website ):
Self. name = name
Self. lang = lang
Self. website = website
Self. email = "qiwsir@gmail.com" # This property is not passed through the Parameter

Info = Person ("qiwsir", "python", "qiwsir. github. io ")
Print "info. name =", info. name
Print "info. lang =", info. lang
Print "info. website =", info. website
Print "info. email =", info. email # info create an instance through self and import the instance Property Data

# Running result

Info. name = qiwsir
Info. lang = python
Info. website = qiwsir. github. io
Info. email = qiwsir@gmail.com # print results

Through this example, we have expanded our understanding of self, that is, it is not only to pass the data imported by parameters within the class, but also to pass self in the constructor. attribute: Specifies the attributes of the self instance object. This attribute is also the attribute of the class instantiation object, that is, the attributes of the class after initialization by the constructor. Therefore, the data of this attribute can also be obtained through info. email in instance info. Here, we can interpret the self image as "both internal and external. Or, as mentioned above, Map info and self, inside and outside the self master.

In fact, the topic of self is not over yet, and it will appear in the method below. It's amazing.

Constructor Parameters

As mentioned above, constructor _ init _ is a function, but it looks a little strange. Then, the operations in the function are still feasible in the constructor. For example:
Def _ init _ (self, * args ):
Pass

This type of parameter: * The args parameter is the same as the previously described function parameter. If you forget to watch the official website, go to review. However, the self parameter is required because it is used to create an instance object.

In many cases, data is not imported from the outside every time. Sometimes some parameters of the constructor are set with default values. If no new data is imported, these default values are applied. For example:
Copy codeThe Code is as follows:
Class Person:
Def _ init _ (self, name, lang = "golang", website = "www.google.com "):
Self. name = name
Self. lang = lang
Self. website = website
Self. email = "qiwsir@gmail.com"

Laoqi = Person ("LaoQi") # import a data name = "LaoQi", other default values
Info = Person ("qiwsir", lang = "python", website = "qiwsir. github. io") # re-import all data

Print "laoqi. name =", laoqi. name
Print "info. name =", info. name
Print "-------"
Print "laoqi. lang =", laoqi. lang
Print "info. lang =", info. lang
Print "-------"
Print "laoqi. website =", laoqi. website
Print "info. website =", info. website

# Running result

Laoqi. name = LaoQi
Info. name = qiwsir
-------
Laoqi. lang = golang
Info. lang = python
-------
Laoqi. website = www.google.com
Info. website = qiwsir. github. io

In this Code, you should first understand the meaning of the phrase "class is the factory of an instance". Two instances are generated through class Person: laoqi and info.

In addition, the default parameter value can be set when the function value is assigned.

At this point, only the basic structure of a class is initially built and class initialization is completed.




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.