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

Python magic method (2):__ init __ (cls[, *args]) method

編輯:Python

Python There are some magical ways to do it , They are always surrounded by double underscores , They are object-oriented Of Python Everything . They are special ways to add magic to your classes , If your object implements ( heavy load ) A magic method , Then this method will be automatically used in special cases Python The call .

function

Initialize instance object .


Parameters

self Represents the object itself , There can also be other parameters .

Return value

You don't need to return a value .


Application scenarios

When you want an object to initialize certain properties when it is created .

Examples of use

class MyText(object):
name = None
age = 18
hobby = None
def __init__(self, name, age, hobby):
self.name = name
self.age = age
self.hobby = hobby
sample = MyText(' A Qiang ', '20', ' Jane ')
print(sample.__dict__)

__init__ Methods are also called constructors , It is the second method that is called automatically when the object is instantiated . If the method is not defined , When an object is instantiated, its parent class will be called automatically __init__ Method .

Superclasses of all classes object, There is a default include pass Of __ init __() Realization , This function is called when the object is initialized , We can choose to achieve , You can also choose not to implement , The general advice is realized , Without implementing the object properties, it will not be initialized .

__init__()  Methods can contain multiple parameters , But it must contain a file named self Parameters of , And must be the first parameter . in other words , The constructor of a class must have at least one self Parameters , Contains only self Parametric __init__() Construction method , Also known as the default constructor of a class .

stay __init__() In the construction method , except self Out of parameters , You can also customize some parameters , Use commas between parameters “,” Segmentation .

__init__ and __new__ The difference between

common :

Both are Python Functions in object-oriented languages ,__new__ Less use ,__init__ It uses more .

similarities and differences :

  • __new__ It is called before the instance is created , Because its task is to create an instance and return the instance object , It's a static method .
  • __init__ It is called when the instance object is created , Then set some initial values of the object properties , It is usually used to initialize a class instance . Is an example method .
  • __new__ First called ,__init__ After the called ,__new__ The return value of ( example ) Pass on to __init__ The first parameter of the method , then __init__ Set some parameters for this instance .

  Additional explanation :

1、 Inherited from object The new type of __new__

2、__new__ At least one parameter cls, Represents the current class , This parameter is instantiated by Python The interpreter automatically recognizes

3、__new__ There must be a return value , Return the instantiated instance , This is achieved by myself __new__ We should pay special attention to it , Sure return Parent class ( adopt super( The name of the class , cls))__new__ The examples come out , Or directly object Of __new__ The examples come out

4、__init__ There is a parameter self, This is this. __new__ The returned instance ,__init__ stay __new__ On the basis of this, we can complete some other initialization actions ,__init__ You don't need to return a value

5、 If __new__ Create an instance of the current class , Automatically called __init__ function , adopt return Statement __new__ The first argument to the function is cls To ensure that it is the current class instance , If it's the class name of another class ,; Then the actual creation returns instances of other classes , In fact, the current class will not be called __init__ function , No other classes will be called __init__ function .

6、 There is no redefinition when defining subclasses __new__() when ,Python The default is to call the immediate parent of the class __new__() Method to construct an instance of the class , If the parent of the class is not overridden __new__(), So it's going to go all the way back to object Of __new__() Method , because object Is the base class for all new classes .

7、 And if you override __new__() Method , Then you are free to choose any other new class ( It must be a new type , Only the new type must have __new__(), Because all the new classes are object The offspring of , And the classic class doesn't have __new__() Method ) Of __new__() Methods to make examples , Including all the previous and future generations of this new class , As long as they don't cause recursive loops . You can't call your own anyway __new__, It must be a dead cycle .

8、 For subclasses __init__, The calling rules follow __new__ It's consistent , Of course, if the subclass and the superclass __init__ Functions want to call , Can be in subclass of __init__ Add the parent class to the function __init__ Function call .

9、 When we use , Use as much as possible __init__ function , Don't customize it __new__ function , Because the two are very different in inheriting and deriving features .

10、 Compare classes to manufacturers ,__new__ The way is to buy raw materials in the early stage ,__init__ The way is on the basis of raw materials , machining , Initialize the product link


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