What exactly does _ init _ in Python do ?, Python _ init __

Source: Internet
Author: User

What exactly does _ init _ in Python do ?, Python _ init __

It is strange to see a function name in Python, __init _ I know that the underlined function will run automatically, but I do not know the specific meaning of its existence ..

Today, we can see <concise Python tutorial> Chapter 1 object-oriented programming, which introduces it as follows: "comments to C ++/Java/C # programmers
All class members (including data members) in Python arePublic, All methods areValid.
Only one exception: if the data member name you use usesDouble underline prefixFor example__privatevarThe name Management System of Python effectively uses it as a private variable.
In this way, there is a convention that if a variable only needs to be used in a class or object, it should be prefixed with a single underscore. Other names are public and can be used by other classes/objects. Remember that this is just a convention and is not required by Python (different from the double-underline prefix ).
Similarly, note that__del__Method andDestructorThe concept is similar. "

I suddenly realized that _ init _ was used as a constructor in the class, which is fixed and written. It seems very rigid and actually makes sense.

  

def __init__(self, name):        '''Initializes the person's data.'''        self.name = name        print '(Initializing %s)' % self.name        # When this person is created, he/she        # adds to the population        Person.population += 1

  nameA variable belongs to an object (it usesselfTherefore, it is an object variable.

  self.nameThe value is specified according to each object, which indicates the essence of the variable as an object.

Remember, youOnlyAvailableselfVariable to refer to the variables and methods of the same object. This is calledAttribute reference.

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.