Create an instance with one of the old Ziko python writing classes _python

Source: Internet
Author: User
Tags in python

Description: This part of the class, I refer to the "Learning Python" a book to explain.

Creating a Class

The method of creating a class is simpler, as follows:

Copy Code code as follows:

Class Person:

Note that the name of a class generally starts with a capital letter, which is a common practice. Of course, if you deliberately do not follow this practice, it may not be, but it will give others to read and even after their own reading brings trouble. Since everyone is walking on the right, you must not sleep in the middle of the road.

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

Copy Code code as follows:

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

In the above class, the first is a function named: __init__ (), note that this function starts with two underscores, then Init, and ends with two underscores. This is a function, just like the function we have learned before. However, this function is a bit strange, it is named "__" Start and end.

Please reader here to clarify a basic concept, class is an object type, and with the previous study of the 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 called person, just as there is an object type list.

In building the person class, the first thing to do is to initialize the type, that is, to illustrate this type of basic structure, once the object of this type is invoked, the first is to run the basic structure of this type, that is, the basic structure of the class person. Just as each of us, in our minds, has an object type such as "person" (corresponding to a class), and once we encounter John (John is a specific person), we first run the basic structure of the Class "human": a nose with two eyes and a mouth under the nose. If John conforms to this basic mechanism, we will not be surprised (no error), if the John does not conform to the basic structure (such as three eyes), we will be surprised (the error).

Since 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. So this function, called a constructor, is tasked with initializing the class.

or return to person this class, if according to the above code, write well, is not __init__ () on the run up? No! At this time has not seen John, must see John to run. The so-called see John, see John such a concrete real person, this action, there is a term in python, called instantiation. Run the __init__ () function immediately after the class person instantiates.

Copy Code code 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 is established, and the constructor declares the basic structure of the 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, and the type of the object is the person type, what is the person type like? That's what __init__ () constructs. When instantiated, the specific data must be passed through the 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, the reference relationship is established with the variable info. Please reader recall the references to variables and objects that you have previously described.

is reader a little dizzy? Class, instance, these two concepts are always followed by learning, and in many OOP models, these two concepts are encountered. To make reader not faint, compare them here (Note: Compare the content, refer to the "Learning Python" book)

Classes and instances
• "class provides default behavior, is an instance of the factory", I think this sentence is very classic, miju the relationship between class and instance. Look at the code above, experience, is this the reason? The so-called factory, is can use the same mold to make a lot of specific products. The class is the mold, and the example is the specific product. So, an instance is the actual object that the program handles.
• Classes are made up of statements, but instances are generated by invoking the class, and each time a class is invoked, 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 (for example, person).

Perhaps the above comparison is not enough to let reader understand classes and examples, it does not matter, continue to learn, in the progress of the elimination of doubt.

The role of self

The careful reader may notice that in the constructor the first argument is self, but there seems to be no such argument when instantiated, so what does self do?

Self is a very magical parameter.

In the person instantiation process, the data "Qiwsir", "Python", "Qiwsir.github.io" through the constructor (__init__ ()) parameters have been deposited into memory, and the data in person type of the appearance of an object, The reference relationship established by this object and the variable info. This process can also be said to be attached to an instance of this data. This allows you to call a data anywhere in the program in the form of a object.attribute, such as Info.name get "Qiwsir" in the program above. This type of invocation is often used in classes and instances, dot number "." Later, a property called a class or instance.

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

As we learn, reader will find that within the class we will write functions that have different functions in the class that have another name, Yue: method. The data passed in through the constructor of the class is also wanted to be used in each method, and it needs to be stored long in the class and can be invoked at any time. To solve this problem, in the class, all incoming data is assigned to a variable, usually the name of the variable is self. Note that this is a habit and a consensus, so reader don't take another name.

The first argument in the constructor, self, is the effect of receiving all the data passed in during the instantiation, which is imported through the parameters following the constructor. Obviously, self should be an example (the exact case is an application instance), because it corresponds to the specific data.

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

Copy Code code 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 happens
Print type (self)

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

Confirmed the reasoning. Self is an instance (precisely the reference variable of an instance).

Self This instance has the same properties as the instance object referenced by the previous info. Next, then, specify the data that corresponds to its properties and attributes. In the code above: Self.name = name, which prescribes a property of the self instance, whose name is also called name, is the data of the property that is equal to the data imported by the constructor's parameter name. Note that the name in Self.name has nothing to do with the constructor's parameter name, both of which are just a coincidence (often coincidental), or that the person who wrote the code is lazy and does not want to take another name. Of course, it is possible to write self.xxxooo = name.

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

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

Copy Code code 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 example, we have expanded our understanding of self, which is not just for passing parameter-imported data within a class, but also in constructors, By Self.attribute, the attribute of the self instance object is specified, which is also the property of the class instantiation object, which is the property that the class has after it is initialized through the constructor. So in the instance info, the data of the attribute can be obtained by Info.email. Here, you can visualize self as "both inside and outside". Or, as mentioned earlier, match info to self, self Lord, info outside.

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

Parameter of constructor

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

This type of argument: *args as described in the previous function arguments, it is not much to say. Forget the reader, please go to review. However, the self parameter is necessary because it is to create an instance object.

Many times, not every time you want to pass the data from the outside, sometimes you set some parameters of the constructor defaults, and if no new data is passed in, the defaults are applied. Like what:

Copy Code code 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, reader first to understand the meaning of the phrase "class is the factory of instance", which generates two instances through the class person: Laoqi, info

In addition, the default parameter values are allowed when looking at the function assignment.

So far, the basic structure of a class is only preliminarily 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.