Introduction to the role of __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 such as __privatevar,python's name management system, it effectively takes 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, note that the __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 pop Ulation    person.population + = 1

The name variable belongs to the object (it uses the self assignment) and therefore is the object's variable

The value of Self.name is specified on a per-object basis, which indicates the nature of the variable it acts as an object.

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.