Python object initialization

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.