Home > Backend Development > Python Tutorial > Introduction to the role of __init__ in Python

Introduction to the role of __init__ in Python

巴扎黑
Release: 2017-09-04 11:34:26
Original
2840 people have browsed it

I saw that there is 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..

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

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

With 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 in a class or object, it should be prefixed with a single underscore. Other names will be regarded as public and can be used by other classes/objects. This is just a convention, not required by Python (unlike the double underscore prefix)

Also, note that the __del__ method is similar to the concept of destructor "

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


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

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

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

The above is the detailed content of Introduction to the role of __init__ in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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