Python's constructor __init__ function

Python's constructor __init__ function

Constructor -initialize objects of this class

  I have used this thing recently, just record its basic usage, and I haven’t studied it in depth. No wonder the readers.


   The class can define a special method called __init__() (the constructor starts and ends with two underscores "_ _"). After a class defines the __init__() method, the __init__() method will be automatically called for the newly generated class instance when the class is instantiated. The constructor is generally used to set the initial value of the object data member or perform other necessary initialization work. If the user does not involve a constructor, Python will provide a default constructor.


For example, define a complex class Complex, the constructor completes the initialization of the object variable

class Complex:
	def __init__ (self, realpart, imagpart) :
		self.r = realpart
		self.i = imagpart

x = Complex(3.0,-4.5)
print(x.r, x.i)

The results of the operation are as follows:
3.0 -4.5

Guess you like

Origin blog.csdn.net/weixin_45386875/article/details/113818538