Home >Backend Development >Python Tutorial >What exactly does __init__ in Python do?
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, Part 2 Introduce it like this: "Note to C++/Java/C# programmers
All class members (including data members) in Python are public, and all methods are valid.
With one exception: if you use If the data member name is 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 used as a private variable. Single underscore prefix. All other names will be public and can be used by other classes/objects. Remember this is just a convention and not required by Python (unlike double underscore prefix)
Also, note __del_. The concept of _method is similar to destructor. "
It suddenly dawned on me that __init__ 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): '''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
name variable belongs to the object (it Assignment using self) is therefore a variable of an object
The value of self.name is specified on a per-object basis, indicating its nature as a variable of an object.