Python basics----Object-oriented programming introduction, classes, and objects

Source: Internet
Author: User

object oriented into introduction

Process-oriented programming

The core is the process (pipeline thinking), the process is the steps to solve the problem, the process-oriented design is like a well-designed pipeline, consider when to deal with what things. The main applications are in places where little modification is done, such as the Linux kernel, git, Apache server, etc.

Advantages: Greatly reduce the design complexity of the program

Cons: Poor scalability, change a place is likely to change multiple places, reaching

Object-Oriented programming: not all programming, just to solve the software extensibility

The core is the object (God-Mind), the object as the basic unit of the program, an object containing the data and the function of manipulating the data. Object-oriented is the computer program as a collection of objects, every object can receive messages from other objects, the execution of a computer program is a series of messages between the various objects passed. The main application in the requirements of the frequent changes in software, general requirements of the changes are concentrated in the user layer, Internet applications, enterprise internal software, games, etc.

Advantages: Solve the problem of poor scalability of the program, the modification of an object will be immediately reflected in the entire program system, such as LOL on a Hero attribute modification (years weakening has never been strengthened)

Cons: Poor controllability, inability to predict program execution results, such as LOL per game results

Classes and objects

The concept of objects

Object is also called instance, is generated by the class, the object is a combination of data properties and method attributes, such as the hero in Lol, a hero is an object, with health value, blue bar attack and other data attributes, but also has qwer four skills belong to the method attribute.

The concept of a class

class contains the same property part of a set of objects, or the hero in Lol, all heroes have names, tags (tank warrior mage), health, blue bar attack, etc., although the specific values are different, but can be included in the class to generate.

In Python, a variable is represented as a data property, and a function is used to represent a method property.

In real life, there are objects after the first class, such as the first people, after the concept of human, and in programming, is the first class, after the object, class generation object.

declare a class: similar to the definition of a function

Defining functions: Using the DEF keyword

1 def functionname (args): 2      ' function document string ' 3       

Definition class: By cless keyword, the name of the class is generally capitalized, in order to distinguish it from the function

1 "2 class Name: 3     ' class of document string ' 4     class body 5 ' ' 6 #我们创建一个类Data类, 7 class Data:8     

Example: Defining a Chinese class

First of all, the characteristics of the Chinese people, the first nationality must belong to China, and then also if the individual, then people will do what (eat and drink to sleep and talk) and so on, and everyone has their own unique attributes, such as the name of the height of birthdays and so on

Pseudo-code Analysis (analysis only):

chinese# For example a common attribute has country= ' china ' #国籍中国language = ' Chinese '  #语言为中文, local languages, minority languages can be classified as unique properties # will be the skill of Def talk (self):    Print (' is talking ') def eat (self):    print (' was eating ') def sleep (self):    print (' was eating ') def work:    Print (' is working ') # and a range of human-contained skills

#特有属性
Name=name
Age=age
Sex=sex

Code Definition: The __INIT__ function and self are described below

1 class Chinese:2     # Common features: Nationality and language 3     country = ' China ' 4     language = ' Chinese ' 5     # __init__ (P1, ' Zhangsan ', ' Man ', min) 6     def __init__ (self,name,sex,age): 7         #只用于初始化的活, cannot have a return value that defines a unique attribute 8         self.name=name #p1. Name= ' Zhangsan ' 9         self.sex=sex #p1. sex= ' man '         self.age=age #p1. age=7311     # Common Skills     def talk (self): 13         print (' is talking ') +     def eat (self): +         print (' is eating ') +     def sleep: +         print (' Is Eating ')     def work (self):         print (' is working ')

Property references for the class:

1 print (chinese.__dict__)         #以字典的方式返回Chinese的所有属性, or use Dir (class name) to query 2 print (chinese.language)         # View Chinese's Language Properties 3 print (chinese.work)         #查看Chinese的work属性4 chinese.language= ' Putonghua '    # Modify the language property of the Class 5 chinese.complexion= ' yellow '     #增加一条肤色属性6 del chinese.complexion          #删除肤色属性

Instantiation (build instance): __init__ function and self description

1 P1=chinese (' Zhangsan ', ' man ', ' name= ')     #生成一个实例, "Zhangsan ' sex= ' man  '  age=732 print (p1.__dict__)       #以字典的方式返回p1的属性, does not contain common properties of the class, only name/sex/age

The class name plus parentheses is an instantiated process, which generates an object called P1.

1 Print (P1.__dict__,type (p1)) 2 #输出结果为3 {' name ': ' Zhangsan ', ' sex ': ' Man ', ' age ': <class ' __main__. Chinese ' >

The result of the p1.__dict__ output is the result of the __init__ function, and the position parameter of the __INIT__ function has four self,name,sex,age, the process of instantiation passed ' Zhangsan ', ' man ', 733 parameters correspond to Name,sex,age, and self is also a positional parameter, function part we know the position parameter must pass the value, here the code automatically will pass the value P1, namely the instance name P1.

And the P1 type is <class ' __main__. Chinese '; If you look at the type of Chinese, you will find the same as P1, meaning that defining a class is defining a type.

Object's Property Reference:

1 print (p1.language)      #p1本身并没有language属性, but it can be found that itself, although not, but from the class can get 2 # print (P1.run ())       #报错, because you and the class do not have this attribute 3 Print (P1.work ()) 4 p1.city= ' Beijing '       #增加一条属性, just against the object itself, will be added to the P1 's property dictionary and will not have an effect on Chinese 5 del p1.city             #删除一条属性

Conclusion:

The data properties of the class can be deleted and modified

Object data properties can be deleted and modified

The object itself does not have a function property, only its own data properties (properties that are initialized by the __INIT__ function or properties that are manually added), but can be called through the class, that is, common features and properties

The common data and functions in the object are the namespace of the reference class

The properties of the object, preferably from their own __dict__ dictionary, if not in their own dictionary, access to the class, if not in the class, error, the properties of their own definition of the other reference to the same properties of the class has no effect

object's usage:

Class chinese:obj_list=[] count=0 country = ' China ' language = ' Chinese ' def __init__ (self,name,sex,age): Self.name=name self.sex=sex self.age=age self.obj_list.append (name) #每次实例化, the instance adds a name to the Pbj_list        Word self.count+=1 #每次实例化, the instance will count+1 def sleep (self): print (' was eating ') def work: Print (' was working ') P1=chinese (' Bob ', ' Man ', ') P2=chinese (' Natasha ', ' Woman ', ") P3=chinese (' Hurry ', ' man ', ') print ( p1.obj_list,p1.__dict__) print (p2.obj_list,p2.__dict__) print (p3.obj_list,p3.__dict__) print (chinese.obj_list) # # # # # # #分割线君 ###### #print (P1.count,id (P1.count)) print (P2.count,id (p2.count)) print (P3.count,id (p3.count)) print ( Chinese.count,id (Chinese.count)) output: [' Bob ', ' Natasha ', ' hurry '] {' name ': ' Bob ', ' sex ': ' Man ', ' age ': ', ' count ': 1}[' Bob ', ' Natasha ', ' hurry ' {' name ': ' Natasha ', ' sex ': ' Woman ', ' age ': ' Count ': 1}[' Bob ', ' Natasha ', ' hurry '] {' name ': ' Hurry ', ' sex ': ' Man ', ' age ': ten, ' Count ': 1}[' Bob ', ' Natasha ', ' HuRry ']1 18186046081 18186046081 18186046080 1818604576 

The results show that each instance has no obj_list, but there are count, one is mutable, one is immutable, so the variable data obj_list in the class can be modified directly, the memory ID will not change, and the immutable data count can only be recalculated, opening up new memory space for reference is built in the properties of the object, not the properties of the class

 1 class Chinese:2 obj_list=[] 3 count=0 4 country = ' China ' 5 language = ' Chinese ' 6 def __init__ (SE Lf,name,sex,age): 7 Self.name=name 8 self.sex=sex 9 Self.age=age10 Chinese.obj_list.append         (name) #每次实例化, the Chinese class adds an instance name to Obj_list chinese.count+=1 #每次实例化, Chinese count+112 def sleep (self): 13 Print (' is eating ') + def work (self): ("is working")-P1=chinese (' Bob ', ' Man ', ')-P2=chinese (' Natasha ', ' Woman ', () P3=chinese (' Hurry ', ' man ', ten) print (p1.obj_list,p1.__dict__) print (p2.obj_list,p2.__ dict__) print (p3.obj_list,p3.__dict__) print (chinese.obj_list) ###### #分割线君 ###### #24 print (P1.count,id ( P1.count) (P2.count,id (P2.count)) print (P3.count,id (p3.count)) print (Chinese.count,id (chinese.count)) 28 29 output results [' Bob ', ' Natasha ', ' hurry '] {' name ': ' Bob ', ' sex ': ' Man ', ' age ': 18}31 [' Bob ', ' Natasha ', ' hurry '] {' name ': ' Natasha ', ' sex ': ' Woman ', ' age ': 28}32 [' Bob ', ' Natasha ', 'Hurry ' {' name ': ' Hurry ', ' sex ': ' Man ', ' age ': 10}33 [' Bob ', ' Natasha ', ' Hurry ']34 3 181860467235 3 181860467236 3 1818604 67237 3 1818604672

The result shows that, during instantiation, the property modification operation of the class itself does not have any effect on the object, and all objects do not contain the Count property and the Obj_list property, which is called by the class.

1 class chinese:2     country = ' China ' 3     language = ' Chinese ' 4     def __init__ (self,name,sex,age): 5         Self.nam E=name 6         self.sex=sex 7         self.age=age 8     def sleep (self): 9         print ('%s is eating '%self.name)-     def Work: one         print ('%s is working '%self.name) P1=chinese (' Bob ', ' Man ', ') ' P2=chinese (' Natasha ', ' Woman ', 28 ) # chinese.work ()    #抛出TypeError15 p1.work () p2.work () #输出结果18 Bob is working19 Natasha are working

The result is that the functions defined in the class are only for the object, and the classes themselves cannot use these functions. class defines only methods, and methods are bound to objects of the

Python basics----Object-oriented programming introduction, classes, and objects

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.