What exactly is __init__ in Python?

Source: Internet
Author: User

It's strange to see a function name in Python, __init__ I know the underlined function will run automatically, but I don't know the exact meaning of it.

See Today << Concise Python Tutorial >> 11th, Object-oriented programming, which describes it as: " annotations to c++/java/c# programmers
All of the class members (including data members) in Python are public and all methods are valid .
There is only one exception: if you use a data member name with a double-underscore prefix , for example __privatevar , Python's name management system effectively uses it as a private variable.
This makes it a rule that if a variable is only meant to be used in a class or object, it should be prefixed with a single underscore. Other names will be public and can be used by other classes/objects. Remember that this is only a convention, not what Python requires (unlike a double underscore prefix).
Similarly, the attention __del__ method is similar to the concept of destructor . "

Suddenly the original __init__ in the class is used as a constructor, fixed also written, seemingly very rigid, in fact, there is a reason

  

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

  nameA variable belongs to an object (it uses an self assignment) and is therefore a variable of an object

  self.nameValues are specified on a per-object basis, which indicates the nature of the variable that it acts as an object.

Remember, you can only use self variables to refer to variables and methods of the same object. This is referred to as the attribute reference .

What exactly is __init__ in Python?

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.