Create an instance from one of the old Python writing classes

  • 2020-04-02 14:14:23
  • OfStack

Note: for this part of the class, I refer to the book "Learning Python".

Create a class

The method to create a class is simple, as follows:


class Person:

  Note that the name of a class usually begins with a capital letter, as is the convention. Of course, it's ok to deliberately break this routine, but it can cause problems for others to read and for yourself to read later. Since everyone walks on the right, you shouldn't have to sleep in the middle of the road.

Next, you usually write a constructor, so before you write this, explain what a constructor is.


class Person:
    def __init__(self, name, lang, website):
        self.name = name
        self.lang = lang
        self.website = website

  In the above class, first rendered is a function called: successively init__(), notice that this function starts with two underscores, then init, and ends with two underscores. This is a function, just like the function we learned before. However, this function is a bit odd, it is named to begin and end with "__".

To be clear, a class is an object type, just like the types of values, strings, lists, etc. For example, the name of the class we're building here is Person, so we're going to try to create an object type that's called Person, just like there's an object type that's called list.

When you build the Person class, the first thing you do is initialize the type, which is to say the basic structure of the type, and once the object of that type is called, the first thing you do is run the basic structure of the type, which is the basic structure of the Person class. Just as each of us has an object type (corresponding to a class) about "person" in our mind, once we meet zhang SAN (zhang SAN is a concrete person), we first run the basic structure of the "person" class: a nose with two eyes and a mouth under the nose. If zhang SAN fits the basic structure, we won't be surprised. If zhang SAN doesn't fit the basic structure (like three eyes), we'll be surprised.

Since the class is constructed by ourselves, the basic structure is also constructed manually by ourselves. In the class, the basic structure is written in the function of s/s (). This function is called a constructor and is responsible for initializing the class.

Returning to the Person class, if you follow the above code, is it already working with the system? No! We haven't seen a SAN yet. We have to see a SAN to run. There's a term in python for seeing a real person, a real person like that, and it's called instantiation. Run the function s/s immediately after the Person class is instantiated.


#!/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")     # instantiation Person
print "info.name=",info.name
print "info.lang=",info.lang
print "info.website=",info.website # The result of the above code: info.name= qiwsir
info.lang= python
info.website= qiwsir.github.io

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

Note: info=Person("qiwsir","python","qiwsir.github.io"), which instantiates the class Person. So you create an object in memory, and the object is of type Person, and what does that Person type look like? S/he s/s s/s/s/s/s/s/s. When instantiating, specific data must be passed in as parameters: name="qiwsir",lang="python",website="qiwsir.github.io". So you have an object in memory that's of type Person, and then you have an assignment statement that establishes a reference to the variable info. Remember the relationship between variables and objects that we've talked about before.

Is the judge a little dizzy? Class, instance, are two concepts that will continue to be studied, and are encountered in many OOP models. To keep the viewer entertained, they are compared here (note: the comparison is based on the book "Learning Python")

Class and instance
  The & # 8226; "The class provides the default behavior and is the factory for the instance," I think is a classic statement that breaks down the relationship between the class and the instance. Look at the code above, feel it, is this the reason? The so-called factory, is can use the same mold to make many specific products. The class is the mold, and the instance is the concrete product. So, an instance is the actual object that the program handles.
  The & # 8226; A class is made up of statements, but an instance is created by calling a class, and every time you call a class, you get a new instance of that class.
  The & # 8226; For the class: class Person, class is an executable statement. If executed, you get a class object and assign that class object to the object name (such as Person).
 
Perhaps the above comparison is not enough to make the reader understand the class and instance, no matter, continue to learn, in the process of eliminating doubts.

The role of the self

Careful observers may have noticed that in the constructor, the first argument is self, but when you instantiate it, it doesn't seem to matter, so what does self do?

Self is an amazing argument.

During the Person instantiation process, the data "qiwsir","python","qiwsir.github. IO "have been stored in memory by the constructor function (s) with the parameters of "qiwsir.github. IO ", and these data exist as a type of Person to form an object, which is a reference relationship with the variable info. The process can also be described as attaching the data to an instance. In this way, you can call some data anywhere in the program in the form of :object.attribute, for example, you can get the data "qiwsir" as "info.name" in the above program. This method of invocation, often used in classes and instances, is called a class or instance property after the dot "."

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

As you go along, you'll notice that inside the class, we'll write a lot of functions that do different things, and these functions have another name inside the class, called methods. Then, the data passed in through the parameters in the constructor of the class also wants to be used in each method, so it needs to be kept in the class for a long time and can be called at any time. To solve this problem, in a class, all incoming data is assigned to a variable, usually self. Note that this is a habit, and is the consensus, so, do not take another name.

The first parameter in the constructor, self, does just that -- it receives all of the data that was passed in during the instantiation and imported through the parameters that follow the constructor. Obviously, self should be an instance (an application instance, to be exact), because what it corresponds to is concrete data.

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


#!/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 happens
        print type(self) # The results
<__main__.Person instance at 0xb74a45cc>
<type 'instance'>

  The reasoning is confirmed. Self is an instance (or rather, a reference variable to the instance).

The instance of self, like the instance object referenced by info, has properties. The next step, then, is to specify its properties and their corresponding data. In the above code: self.name = name, is a property that specifies the self instance, the name of this property is also called name, the data of this property is equal to the data imported by the constructor parameter name. Note that the name in self.name has nothing to do with the constructor parameter name, they're the same, but it's just a coincidence (often a coincidence), or that the person writing the code is lazy and doesn't want to give it another name. Of course, if you write self.xxxooo = name, you can.

Actually, it's a little bit easier to think about it from an effect point of view, which is that the instance info of the class corresponds to self, info imports all the data of the instance properties through self.

Of course, self's property data doesn't have to be passed in as an argument, and it can be set in the constructor itself. Such as:


#!/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 in as a 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 through self Create an instance and import the instance property data # The results info.name= qiwsir
info.lang= python
info.website= qiwsir.github.io
info.email= qiwsir@gmail.com    # Print the result

  Through this example, actually let us expand the knowledge of the self, is it just for passing parameters within the class of the imported data, but also in the constructor, through the self, the attribute, specified the self instance object attribute, this property is also the class instantiation object properties, namely as a class through the constructor after initialization of the attribute. So in the instance info, the data of this attribute can also be obtained through info.email. Here, self can be figuratively understood as "both inside and outside". Or, as mentioned earlier, you can correspond info to self, self inside, info outside.

In fact, self is not finished yet, and it will come up later in the method. It's really amazing.

Arguments to the constructor

As already mentioned, the constructor function is a function with a somewhat odd look. So, the operation in the function is still valid in the constructor. Such as:
Def __init__ (self, * args) :
      pass

  This type of parameter: *args is the same as the function parameter described earlier, I won't say much more. You forgot to review, please. However, the self parameter is required because it is to create the instance object.

Most of the time, instead of passing in data from the outside every time, some of the constructor's parameters are set to default values, which are applied if no new data is passed in. Such as:


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 the 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 # The results 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, the first thing the viewer needs to understand is the meaning of the phrase "class is instance factory", which generates two instances through the Person class: laoqi and info

Also, in the case of function assignments, default parameter values are allowed.

So far, we have only preliminarily built the basic structure of a class and completed the initialization of the class.


Related articles: