Python: The Meaning of self and __init__ + why you have self and __init__

Source: Internet
Author: User
Tags variable scope

Python: The Meaning of self and __init__ + why have self and __init__ backgrounds

Reply:

I wrote some python tutorials that need to be able to see

Questions from Songshoujiong:

What is the meaning of self,__init__ in python?

Why do you have to have self,__init these things?

Before you explain, let's say a few words.

1. So far, although I have written not very little Python code, but there is really not too much contact with self and __init__ these two things.

Can only be considered to understand.

2. In order to understand its meaning, now learn to sell, to see some information, and then sorted out.

Among them, it is possible to understand the mistake, but also ask the master correct.

3. Before explaining the meaning, speak first about the self and __init__ in Python:

Personal advice is that a lot of things, when you have a demand, and then to use, the thing is valuable, you will be easier to understand;

Otherwise, temporary contact is not, in fact, it can be put aside, and so on later encountered.

Otherwise, now to work hard to learn, although good attitude, but because there is no relevant programming practice, that is, there is not enough code to practice, the understanding of the concept, it is inevitable difficult to go deep.

Therefore, the suggestions for self and __init__ in Python are:

If you're going to write Python code and go to the process of learning Python, before you encounter it,

For example, like me, has not been how to write the real class, then it is also possible to temporarily ignore these things;

When you need to write classes later, to learn more about, understand, understand its meaning.

4. The following content, for you, indeed encountered self,__init__, when the need to understand the meaning of the time, provide some reference.

5. Before looking at the explanations below, you should first understand the concepts of classes (class) and instantiated objects of classes (object, also known as instance instance).

If you do not understand, you can refer to my summary:

"Organizing" the basics of object-oriented: Class-Classes, Objects (object), instances (Instance)

What is the meaning of self and __init__ in Python + why Self in self and __init__python

In Python's class code, you often see the first parameter in the function, which is self.

And the function inside the class, access the corresponding variable (read or write), and call the corresponding function, are

Self.valuename

Self.function ()

The form.

Let's explain what self means:

The meaning of self in Python

Self, English word meaning is obvious, express oneself, itself.

There are several potential meanings here:

1. Here the self, refers to the instance instance itself.

2. At the same time, because of the word "self", it is compared with the relative "other" and said.

And here's the other, referring to the classes class, and other variables, such as local variables, global variables, and so on.

The self here, is an object, and object.

is an instance of the current class.

Therefore, the corresponding

Self.valuename

Self.function ()

In the

ValueName: Represents the Self object, which is the variable for the instance. Other, class variables, global variables, local variables, are relative.

Function: Indicates that it is called the Self object, that is, the instance's functions. It is relative to other global functions.

Why you should have self in Python

In fact, it is basically clear why it is necessary to have self.

That is:

In the code (function) of the class, you need to access the variables and functions in the current instance, that is, to access the instance:

    • The corresponding variable (property): Instance.properynam, to read the previous value and write a new value

    • Call the corresponding function: Instance.function (), that is, perform the corresponding action

The variable that needs to access the instance and the function that invokes the instance, of course need corresponding instance instance object itself

As in Python, the first parameter of the function must be the instance object itself, and it is recommended that the name be written as self

So, we need self (need to use self)

If you do not use self, that is, in code, after you remove self, the variables used in that notation are actually not what you want, not the variables and functions in the real instance, but the variables and functions that have been accessed to other parts.

It can even cause subsequent unreachable errors due to the absence of a suitable initialization instance variable.

Below, the code shows what errors will occur if you remove self or if you do not use self properly.

If the corresponding instance variable is not initialized in __init__, the subsequent reference to the instance variable will cause an error

The following code shows the complete demonstration that if the instance variable is not properly initialized in the original __init__ function of class classes, it will cause the subsequent absence of the variable to be available, resulting in a attributeerror error:

#!/usr/bin/python#-*-coding:utf-8-*-"" "----------------------------------------------------------------------- --------Function: "Grooming" python: the Meaning of self and init__ + why you have self and __init__http://www.crifan.com/summary_the_meaning_of_self _and___init___in_python_and_why_need_them author:crifanverison:2012-11-27-------------------------------------- -----------------------------------------"" #注: Here the global variable name, written as name, just for demonstration purposes # In fact, good programming style, should be written like Gname name, To indicate that the variable is a variable of global name = "Whole global name";                 Class Person:def __init__ (Self, newpersionname): #self. name = Newpersionname;                 #1. If the Self.name #那么此处的name is not written here, it is just a local temporary variable in the __INIT__ function name #和全局中的name, not a half-penny relationship name = Newpersionname; #此处只是为了代码演示, while using the local variable name, #不过需要注意的是, it is obvious here that the next code does not take advantage of the local variable name #则就导致了 here, where the name variable is actually wasted , there is no use to Def sayyourname (self): #此处由于找不到实例中的name变量, so there will be an error: #AttributeError: person instance have no attrib Ute ' name ' print ' My name is%s '% (Self.name);    Def selfandinitdemo (): Persioninstance = Person ("Crifan");     Persioninstance.sayyourname ();    ############################################################################## #if __name__== "__main__": Selfandinitdemo ();

From the above code is visible, because in the class initialization (instantiation) of the __init__ function, do not give self.name set the value, so that the instance, there is no name this variable, resulting in subsequent visits to the self.name, there will be attributeerror error.

Corresponding, if written self.name, then the meaning is correct, that is, when the initialization, the new additions to the instance, and the normal set of the correct value newpersionname, so the subsequent to go through Self.name, you can access to the current instance of the correct variable name.

The appropriate code for the correct wording is as follows:

#!/usr/bin/python#-*-coding:utf-8-*-"" "----------------------------------------------------------------------- --------Function: "Grooming" python: the Meaning of self and init__ + why you have self and __init__http://www.crifan.com/summary_the_meaning_of_self _and___init___in_python_and_why_need_them author:crifanverison:2012-11-27-------------------------------------- -----------------------------------------"" #注: Here the global variable name, written as name, just for demonstration purposes # In fact, good programming style, should be written like Gname name, To indicate that the variable is a variable of global name = "Whole global name"; Class Person:def __init__ (Self, newpersionname): #此处正确的, by accessing the form of Self.name, implemented by: #1. Adds the name variable # to the instance     2. And assigns the initial value to name, for newpersionname self.name = newpersionname;        def sayyourname (self): #此处由于开始正确的初始化了self对象, which has the name variable, so the name value can be correctly accessed here, it can be correctly output: #My name is Crifan print ' My name is%s '% (self.name);    Def selfandinitdemo (): Persioninstance = Person ("Crifan");     Persioninstance.sayyourname (); ############################################################################## #if __name__== "__main__": Selfandinitdemo (); 

In the function, the corresponding variable is used, although the code can be run, but it is actually used, not the variable in the instance

Sometimes, although you write code that can run, but the variable used, because there is no add self, is actually used not the instance of the variable, but other variables.

This type of problem is primarily related to the scope of variables in Python, but the example here is also related to whether to use self:

#!/usr/bin/python#-*-coding:utf-8-*-"" "----------------------------------------------------------------------- --------Function: "Grooming" python: the Meaning of self and init__ + why you have self and __init__http://www.crifan.com/summary_the_meaning_of_self _and___init___in_python_and_why_need_them author:crifanverison:2012-11-27-------------------------------------- -----------------------------------------"" #注: Here the global variable name, written as name, just for demonstration purposes # In fact, good programming style, should be written like Gname name, To indicate that the variable is a variable of global name = "Whole global name";                 Class Person:name = "Class Global name" Def __init__ (Self, newpersionname): #self. name = Newpersionname;  #此处, not using the Self.name #而使得此处的name, is actually still the local variable name #虽然此处赋值了, but is not used later, belongs to the wasted local variable name name =     Newpersionname; def sayyourname (self): #此处, there is no such thing as before: #AttributeError: instance has no attribute ' name ' #那是 Because, although the current instance of self, does not initialize the corresponding name variable in __init__, the instance self does not have a corresponding name variable #但是由于实例所对应的类Person, there is a corresponding name variable, so it is also possible to execute the code normally #对应的 HereSelf.name, which is actually person.name print ' My name is%s '% (self.name); #-A class global name print ' name within class person is actually the global name:%s '% (name); #-> Whole global name print "Only access person ' s name via person.name=%s"% (person.name);    #-A class global name Def selfandinitdemo (): Persioninstance = Person ("Crifan");    Persioninstance.sayyourname (); Print "Whole global name is%s"% (name); #-Whole global name ############################################################################## #if __name__ = = "__main__": Selfandinitdemo ();

Where, it is visible, here begins __init__, does not initialize the corresponding name to the self instance

And in the back of the function sayyourname, although you can call to Self.name without a attributeerror error

But actually the value here is not what is expected, the name passed in, that is, "Crifan", but the value of name in the class, which is "class global name".

For a detailed explanation of the scope of variables in Python, refer to:

Scope of variables in "grooming" python (variable Scope)

The __init__ in Python

In Python, it is often seen that in many classes, there is a __init__ function.

Let's explain the meaning of __init__.

The meaning of __init__ in Python

The first thing to look at is the init word itself, the meaning of initialization.

And the meaning of __init__, as its word intended, is used to initialize.

But who is it to initialize?

Obviously, it is to initialize the corresponding class classes themselves.

Why you should have __init__ in Python

My understanding is that the emergence of __init__ has two main roles:

General common initialization, my understanding, may have two main aspects:

Support initialization of classes with parameters

This usage, feel like, in other languages, for class initialization, you can run the same as passing different parameters;

The code demonstrates the following:

#!/usr/bin/python#-*-coding:utf-8-*-"" "----------------------------------------------------------------------- --------Function: "Grooming" python: the Meaning of self and init__ + why you have self and __init__http://www.crifan.com/summary_the_meaning_of_self _and___init___in_python_and_why_need_them author:crifanverison:2012-11-27-------------------------------------- -----------------------------------------"" "Class Person:def __init__ (Self, newpersionname): #在开始初始化新的类Class的示     Example instance, to the corresponding, different instance, set different names (person name) Self.name = Newpersionname; def sayyourname (self): #不同的Person的示例, call the same method when you say your name, the results are corresponding to their own, different names print ' My name is%s '% (self.name) ;    #My name is Crifan def initdemo (): Persioninstance = Person ("Crifan");     Persioninstance.sayyourname (); ############################################################################## #if __name__== "__main__": InitDemo ();

Which is the class for the person,

Different examples, when initializing, pass a corresponding parameter, so that different person, will have their own different names.

This, at least, looks, somewhat like, in other languages, passing specific parameters to initialize the class.

Implementing the initialization of the class itself related content

When a class, a little bit more complicated, or internal functions need to be used, often need to use your class before they instantiate you, to do some basic, related to their own classes, initialization aspects of the work.

And this part of the work is often put into the __init__ function.

In other words, before you use someone else's class (variables and functions), always give someone a chance to do some preparatory work before they can serve you.

This concept, relatively or very well understood, will not be more than repeat.

Demo code is not necessary, because the above code, also can be considered as an example of this, different people, should have different names, and to different people to set different names, but also need to call Sayyourname before the first initialization of the good.

Resources


1. Using the __init__ method

2. Know when to use self and __init__

3.Python ' self ' explained

4. Python __init__ and self What does they do?

Python: The Meaning of self and __init__ + why you have self and __init__

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.