程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

In Python__ init__ What is the popular explanation of?

編輯:Python

author : honor one's ancestors with sacrifices ·J
link :https://www.zhihu.com/question/46973549/answer/767530541
source : You know
The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source .

 

As a typical object-oriented Language ,Python in class Of Definition and Use Is an indispensable part of knowledge . Have object-oriented experience 、 Yes class and example People whose concept is clear enough , Study Python This set of definition rules is just the transfer of grammar . But for novice Xiaobai , To cross... Relatively quickly __init__ This ridge , It's better to combine a simple example .

To create a “ Student ” class For example , The simplest statement is

class Student():
pass

Of course , The class thus defined does not contain any predefined data and functions . Except for the name Student outside , It doesn't show any “ Student ” Should have the characteristics of . But it is available , After the above code runs , Through something like

stu_1 = Student()

Such a statement , We can create one “ Student ” example , That is, a specific “ Student ” object .

adopt class Class defined by statement Student, It's like a “ The mould ”, It can define the various characteristics that a student should have ( There is no specific definition here );

And in the class name Student Followed by parentheses (), Form a Similar to function call In the form of Student(), Then a program called Instantiation The process of , That is, according to the defined rules , Create a student object that contains specific data ( example ).

In order to use the created student instance stu_1, We can continue to add or modify properties for it , For example, add a group of grades scores , Consists of three integers :

stu_1.scores = [80, 90, 85]

But there are obviously many problems , Once we need to deal with many student examples , such as stu_2, stu_3, ..., This not only brings trouble in writing , It's also easy to make mistakes , In case somewhere scores dial the wrong number , Or just forget , The corresponding student examples will lack the correct scores attribute . what's more , In this way scores Attributes are exposed , Its use is completely controlled by the outside , It didn't work “ encapsulation ” The effect of , It's neither convenient nor reliable .

A natural solution is to allow us to execute the instantiation process Student() when Pass in some parameters , To easily and correctly initialize / Set some property values , So how to define this initialization behavior ? The answer is to define a... Inside the class __init__ function . At this time ,Student The definition of will become ( Let's start with a comment __init__ Position in function ).

class Student():
def __init__(self, score1, score2, score3):
# Related initialization statements 

Definition __init__ after , The process of executing instantiation must become Student(arg1, arg2, arg3), The new instance itself , With the parameters , Will be passed on to __init__ Function automatically and executes it . therefore __init__ The argument list of the function will have one more item at the beginning , It always refers to the new instance object ,Python Syntax requires this parameter There must be , And the name is arbitrary , It's customary to call it self.

The new instance is passed to self after , You can go to __init__ Function to create and initialize its properties , Like before scores, It can be written as

class Student():
def __init__(self, score1, score2, score3):
self.scores = [score1, score2, score3]

here , To create student instances with specific grades , Just need

stu_1 = Student(80, 90, 85)

here ,stu_1 Will already have a set scores attribute . And because of __init__ Specifies the parameters when instantiating , If the number of parameters passed in is incorrect , The interpreter can report an error and remind . You can also add necessary parameter checks inside it , To avoid incorrect or unreasonable parameter passing .

In other ways , __init__ It's just like an ordinary function . Considering that novices may be interested in “ function ” It's also very vague , Here are some special points “ It's no different ” The place of :
Independent namespace , in other words All newly introduced variables in the function are local variables , For this function, the newly created instance object only passes the first parameter self From the outside , Therefore, regardless of setting or using its properties, we have to use self.< Property name >. If the above initialization statement is written as
scores = [score1, score2, score3]( Less self.),
You just create a... Inside the function scores Variable , It will disappear after the function is executed , It has no effect on the new instance ;
Corresponding to this , self Property name and other names in the function ( Including the parameters ) There is no conflict , So you may often see this kind of writing , It's correct and standard .
class Student():
def __init__(self, name, scores):
# Attribute is added here name, And take all the scores as a parameter scores Pass in
# self.name yes self Properties of , A separate name Is a local variable in a function , Parameters are also local variables
self.name = name
if len(scores) == 3:
self.scores = scores
else:
self.scores = [0] * 3
It can be set from the second parameter Variable length parameter The default value is etc. , Accordingly, the instantiation process will be allowed Student() Flexibly pass in the required number of parameters ;
other ……

Speaking of the end ,__init__ There is still a special thing , That's it Return value... Is not allowed . If your __init__ If it's too complicated and may end early , Use A separate return Just fine , Don't take the return value .

The execution result of the above code is as follows :


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved