To create an instance with one of the old Ziko Python authoring classes

Source: Internet
Author: User
Description: For this part of the class, I refer to the "Learning Python" book.

Create Class

The method of creating a class is relatively straightforward, as follows:

The code is as follows:


Class Person:

Note that the name of the class is generally preceded by uppercase letters, which is customary. Of course, if you deliberately do not follow this practice, it is not a problem, but it will give others to read and even their own future reading caused trouble. Since everyone is walking on the right, you must not sleep in the middle of the road.

Next, write the constructor, and before you write the function, explain what the constructor is.

The code is as follows:


Class Person:
def __init__ (self, name, Lang, website):
Self.name = Name
Self.lang = Lang
Self.website = website

The above class, first rendered is a function named: __init__ (), note that the function is to start with two underscores, then Init, and finally end with two underscores. This is a function, just like the function we learned before. However, this function is a bit strange, its name is "__" start and end.

Please crossing here to clarify a basic concept, the class is an object type, and the same as the previous learning values, strings, lists and so on type. For example, the class name built here is called person, so we are trying to create an object type that is called person, just as there is an object type of list.

When building the person class, the first thing to do is to initialize this type, that is, to illustrate the basic structure of this type, once the object of this type is called, the first is to run the basic structure of this type, that is, the basic structure of the class person. It's like each of us, in the mind, has a kind of object type (corresponding to a class), and once we encounter Zhang San (Zhang San is a specific person), we first run the basic structure of the Class "human": a nose with two eyes and a mouth under his nose. If Zhang San meets this basic body, we will not be surprised (no error), if Zhang San does not conform to this basic structure (such as three eyes), we will be surprised (error).

Since the classes are constructed by ourselves, the basic structure is also constructed manually by ourselves. In a class, the basic structure is written in the __init__ () function. Therefore, this function is called a constructor, which is responsible for the task of initializing the class.

or return to person this class, if according to the above code, write well, is not __init__ () to run up? No! You don't see Zhang San yet, you have to see Zhang San to run. So-called See Zhang San, see Zhang San such a concrete real person, this action, there is a term in python, called instantiation. Run the __init__ () function immediately after the class person is instantiated.

The 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") #实例化Person
Print "Info.name=", Info.name
Print "info.lang=", Info.lang
Print "info.website=", Info.website

#上面代码的运行结果:

Info.name= Qiwsir
info.lang= python
Info.website= Qiwsir.github.io

In the above code, the class person, the constructor, declares the basic structure of this class: Name,lang,website.

Note: Info=person ("Qiwsir", "Python", "Qiwsir.github.io"), this sentence is to instantiate the class person. That is, an object is created in memory, the type of the object is the person type, what does this person type look like? That's what __init__ () constructs. When instantiating, you must pass in the specific data by parameter: Name= "Qiwsir", lang= "Python", website= "Qiwsir.github.io". So there is an object in memory, the type of the object is person, and then through the assignment statement, with the variable info to establish a reference relationship. Please crossing recall references to variables and objects that have been previously described.

Is crossing a little dizzy? Classes, instances, these two concepts will always accompany the subsequent learning, and in many OOP models, you will encounter these two concepts. To make crossing not faint, compare them here (note: The content of the comparison, referring to the book "Learning Python")

Classes and instances
• "class provides the default behavior, is the factory of the instance", I think this sentence is very classic, lay bare the relationship between class and instance. Look at the above code, experience, is not this reason? The so-called factory, is can use the same mold to make a lot of specific products. Class is the mold, the example is the specific product. Therefore, the instance is the actual object that the program handles.
• A class is made up of statements, but an instance is generated by invoking a class, and each time a class is called, a new instance of the class is obtained.
• For classes: Class Person,class is an executable statement. If executed, a class object is obtained and the class object is assigned a value to the object name (such as person).

Perhaps the above comparison is not enough to let crossing understand classes and instances, it's OK, continue to learn, in the forward to eliminate doubts.

The role of self

Careful crossing may have noticed that in the constructor, the first argument is self, but when instantiated, there seems to be no such argument, so what does self do?

Self is a very magical parameter.

In the process of person instantiation, the data "Qiwsir", "Python", "Qiwsir.github.io" through the constructor (__init__ ()) parameters have been deposited into memory, and the data in the face of the person type exists as an object, This object and variable info establish a referential relationship. This process can also be said to append this data to an instance. This allows the data to be called from anywhere in the program in the form of object.attribute, such as the info.name of the "Qiwsir" in the program above. This method of invocation is often used in classes and instances, with the dot "." The properties of the class or instance are referred to later.

This is in the program, and is outside of the class. What if you want to use the incoming data somewhere inside the class?

As the study progresses, crossing will find that within the class, we will write functions of many different functions, which have another name in the class, Yue: Method. So, the data passed in through the arguments in the class's constructor also wants to be used in each method, and it needs to be persisted in the class and can be called at any time. To solve this problem, in a class, all incoming data is assigned to a variable, and the name of the variable is usually self. Note that this is a habit and consensus, so crossing don't have to take another name.

The first parameter in the constructor, self, is the function that receives all the data that is passed in during the instantiation, which is imported through the parameters that follow the constructor. Obviously, self should be an example (the exact argument is an application instance), because it corresponds to the specific data.

If you add two sentences to the above class, look at the effect:

The 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 #打印 to see what results
Print type (self)

#运行结果
<__main__. Person instance at 0xb74a45cc>

Confirmed the reasoning. Self is an instance (that is, the reference variable of an instance, exactly).

Self This instance has properties as well as the instance object referenced by the info mentioned earlier. Then, the data corresponding to its properties and attributes is defined next. In the code above: Self.name = name, which specifies a property of the self instance, the name of this property is also called name, and the data of this property equals the data imported by the constructor's parameter name. Note that the name and constructor parameters in Self.name name have nothing to do with it, they are just like a coincidence (often coincidental), or the person who writes the code is lazy and does not want to have another name, without him. Of course, it is also possible to write self.xxxooo = name.

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

Of course, Self's property data does not have to be passed in by a parameter, or it can be set in the constructor itself. Like what:

The 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" #这个属性不是通过参数传入的

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通过self建立实例, and import instance property data

#运行结果

Info.name= Qiwsir
info.lang= python
Info.website= Qiwsir.github.io
Info.email= qiwsir@gmail.com #打印结果

In this case, we have expanded our understanding of self, that is, it is not just for passing parameter-imported data inside a class, but also in constructors, The properties of the self instance object are defined by Self.attribute, which is also the property of the class instantiation object, which is the property that the class has after it is initialized by the constructor. So in instance info, the data for this property is also available through Info.email. In this case, self can be understood as "internal and external repair". Or, as mentioned earlier, the info and self correspond, the self in the main, and the info outside.

In fact, the topic of self is not over yet, and it will appear in the following methods. It's really magical.

Parameters of the constructor function

As I've already said, the constructor __init__ is a function, but looks a little odd. The operation in the function, then, is still possible in the constructor. Like what:
def __init__ (Self,*args):
Pass

This type of parameter: *args is the same as the previous function argument, and it's not much to say. Forget the crossing, please go to review. However, the self parameter is required because it is going to build the instance object.

Most of the time, not every time you have to pass data from the outside, sometimes you will set some parameters of the constructor default values, if no new data passed in, the default values are applied. Like what:

The 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") #导入一个数据name = "Laoqi", other default values
info = person ("Qiwsir", lang= "Python", website= "Qiwsir.github.io") #全部重新导入数据

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

#运行结果

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, crossing first to understand, "class is the factory of the instance", the meaning of the sentence, through the class person generated two instances: Laoqi, Info

In addition, the default parameter values are allowed to be set when looking at function assignments.

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

  • 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.