After the Python object is created, the object needs to be initialized. Python has a constructor and an initialization function:
1, the constructor __new__, accepts only one parameter, that is, the class itself (it will be called before the object is constructed, so there is no self argument), so it returns the object that was just created. It is seldom used in daily programming.
2, initialization function __init__, often used. For example, we add an initialization function to the point class that requires the user to provide the x and Y parameters when instantiating the object.
class Point : def __init__ (self, x, y): self.move (x, y) def Move (self,x, y): = x = y def Reset (self): self.move (0, 0)# constructs apoint point = Point (3, 5) Print(point.x, Point.y)#
If the call to the point object does not contain an appropriate initialization parameter, an error such as "insufficient arguments" is prompted. If you call the point class above, run the following
>>> A = point (3 " <STDIN> ", Line 1, in <module>typeerror: __init__ () Missing 1 required positional argument: y " >>> a = Point (3, 4, 5< Span style= "COLOR: #000000" >) Traceback (most recent call last): File " <STDIN> , Line 1, in <module>typeerror: __init__ () takes 3 positional arguments but 4 were given
If you do not want two parameters to be required, you can do so by setting the initialization function to the default value. If you change the code of the __init__ at the following:
class Point : def __init__ (self, x = 0, y = 0): self.move (x, y)
Python object initialization