Introduction to __init__ methods in Python

Source: Internet
Author: User

The __init__ method runs immediately when an object of the class is established. This method can be used to initialize your object with some of the things you want. Note that the start and end of this name are double underlines.
code example:
#!/usr/bin/python
# Filename:class_init.py
Class Person:
def __init__ (self, name):
Self.name = Name
def sayhi (self):
Print Hello, my name is, Self.name

p = person (Swaroop)
P.sayhi ()

# This short example can also is written as person (Swaroop). Sayhi ()

(source file: code/class_init.py)

Output
$ python class_init.py
Hello, my name is Swaroop

How it works
Here, we define the __init__ method to take a parameter name (as well as the normal argument self). In this __init__, we just create a new domain, also known as name. Note that they are two different variables, although they have the same name. The dot number allows us to differentiate between them.

Most importantly, we do not specifically call the __init__ method, but when creating a new instance of a class, include the parameters in parentheses followed by the class name, which is passed to the __init__ method. This is the important point of this method.

Now, we are able to use the Self.name domain in our methods. This has been verified in the Sayhi method.
Comments to the c/java/c# programmer
The __init__ method is similar to constructor in C, C #, and Java

Introduction to __init__ methods in Python

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.