Python--__init__ method

Source: Internet
Author: User

I. Description

The __init__ method is used to customize its own unique features for an object

Second, the sample code is as follows

1 classluffystudent ():2School ='luffycity'3 4     def __init__(self, name, sex, age):5Self. Name =name6Self. Sex =Sex7Self. Age = Age8 9     defLearn (self):Ten         Print('is learning') One  A     defEat (self): -         Print('is eating') -  the     defSleep (self): -         Print('is sleeping')

The resulting object code is as follows:

1 stu1 = luffystudent (' Wang Yi  ' female ')  # Equivalent to luffystudent.__init__ (stu1, ' Wang Yi Ya ', ' female ', 18)

After adding the __init__ method, the following steps are instantiated for the class:

1, first produce an empty object, STU1

2, luffystudent.__init__ (stu1, ' Wang Yi Ya ', ' female ', 18)

To view the STU1 namespace:

1 Print (STU1. __dict__)

The results are as follows:

{' Name ': ' Wang Yi Ya ', ' Sex ': ' Female ', ' age ': 18}

This shows that the object has been tailored to its own unique characteristics.

To view the data properties of an object, the code is as follows:

1 Print (STU1. Name)2print(stu1. SEX)3print(stu1. Age)

The results are as follows:

Wang Yi Ya
Woman
18

Change the data properties of the object, with the following code:

1 ' Lee ya ' 2 Print (STU1. Name)

The results are as follows:

Lee ya

Delete the data properties of the object, as follows:

1 del STU1. Name2print(stu1.  __dict__)

The results are as follows:

{' Sex ': ' Female ', ' age ': 18}

To increase the object's data properties, the code is as follows:

1 ' Python Development ' 2 Print (STU1. __dict__)

The results are as follows:

{' Sex ': ' Female ', ' age ': ' class_name ': ' Python development '}

Python--__init__ method

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.