What exactly does _ init _ in Python do ?, Python _ init __
It is strange to see a function name in Python, __init _ I know that the underlined function will run automatically, but I do not know the specific meaning of its existence ..
Today, we can see <concise Python tutorial> Chapter 1 object-oriented programming, which introduces it as follows: "comments to C ++/Java/C # programmers
All class members (including data members) in Python arePublic, All methods areValid.
Only one exception: if the data member name you use usesDouble underline prefixFor example__privatevar
The name Management System of Python effectively uses it as a private variable.
In this way, there is a convention that if a variable only needs to be used in a class or object, it should be prefixed with a single underscore. Other names are public and can be used by other classes/objects. Remember that this is just a convention and is not required by Python (different from the double-underline prefix ).
Similarly, note that__del__
Method andDestructorThe concept is similar. "
I suddenly realized that _ init _ was used as a constructor in the class, which is fixed and written. It seems very rigid and 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
A variable belongs to an object (it usesself
Therefore, it is an object variable.
self.name
The value is specified according to each object, which indicates the essence of the variable as an object.
Remember, youOnlyAvailableself
Variable to refer to the variables and methods of the same object. This is calledAttribute reference.