What exactly does _ init _ in Python do?

Source: Internet
Author: User
What exactly does _ init _ in Python do? 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 ..


See Today < <Concise python tutorial> > Chapter 4 Object-oriented programming introduces it as follows: "comments to C ++/Java/C # programmers

All class members (including data members) in Python are public and all methods are valid.

Only one exception: if you use a data member name with a double-underline prefix such as _ privatevar, the Python name management system will effectively use 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, the _ del _ method is similar to the destructor method. "

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

The name variable belongs to the object (which uses self assignment), so it is the variable of the object.

The value of self. name is specified based on each object, which indicates its nature as the object variable.

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.