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