What exactly does __init__ in Python do?

高洛峰
Release: 2016-10-18 09:03:42
Original
1092 people have browsed it

I saw a function with a strange name in Python, __init__. I know that the underlined function will run automatically, but I don’t know the specific meaning of its existence..


I saw it today>Chapter 11 Object-Oriented Programming, introduces it like this: "Note to C++/Java/C# programmers

All 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 prefixed with a double underscore such as __privatevar, Python's name management system will effectively treat it as a private variable

There is a convention that if a variable is only used within a class or object, It should be prefixed with a single underscore. All other names will be public and can be used by other classes/objects. Remember that this is just a convention and is not required by Python (unlike the double underscore prefix). Note that the __del__ method is similar to the concept of destructor. "

It suddenly dawned on me that __init__ is used as a constructor in the class, and it is written in a fixed way. It seems very rigid, but it actually makes sense

name variable belongs to Objects (which are assigned using self) are therefore variables of objects

The value of self.name is specified on a per-object basis, indicating its nature as a variable of an object.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template