Concepts of classes and objects
Class is the most important concept of object-oriented design, which is the combination of feature and skill, while class is a combination of features and skills with similar objects.
- In the real world: there must be objects first, then there are classes
- In the program: Be sure to define the class first, then produce the object
在Python中程序中的类用class关键字定义,而在程序中特征用变量标识,技能用函数标识,因而类中最常见的无非是:变量和函数的定义
ClassStudent: School=' xxxxx 'DefLearn(Selfprint ( ' is learning ' ) def eatprint ( ' is eating ' ) def sleep (Selfprint ' is sleeping ' )
Attention:
- The class can have arbitrary Python code that executes during the class definition phase, resulting in a new namespace that holds the class's variable name and function name, which can be viewed through student.__dict__
- The name defined in the class is the property of the class, and the point is the syntax for accessing the property.
- For the classic class we can manipulate the name of the class namespace through the dictionary, but the new class has limitations
Use of the class
- Referencing the properties of a class
OldboyStudent.school #查OldboyStudent.school=‘Oldboy‘ #改OldboyStudent.x=1 #增del OldboyStudent.x #删
- Call the class, or instantiate it, to get the object in the program
s1=Student()s2=Student()s3=Student()如此,s1、s2、s3都一样了,而这三者除了相似的属性之外还各种不同的属性,这就用到了__init__
This method is executed after the object has been generated, only to initialize the object, can have arbitrary code, but must not have a return valueClassOldboystudent:......Def__init__(Self, name, age, sex.name< Span class= "token operator" >=name self.age=age self< Span class= "token punctuation" >.sex=sex ..s1=student (, ' man ' ,28) # Call the class first to produce the empty object S1, and then call student.__init__ (S1, ' rain ', ' Male ', ')
s2=oldboystudent ' southernmost ' , ' female ' Span class= "token punctuation" >,38)
< Span class= "token punctuation" >
Use of objects
The namespace of the object can be viewed with s2.__dict__, viewing the result as{' Name ':' Southernmost ' ' age ' : ' sex ' 38}s2.name = ' Wang San ' change, equivalent to s2.__dict__[ ' Name ']= ' Wang San ' s2.course= ' Python ' del s2.course Delete, equivalent to S2.__dict__.pop (' course ')
< Span class= "token punctuation" > < Span class= "token punctuation" >
Python base Classes and objects