I. Object-oriented design significance
Process-oriented program design is the core of process (pipeline thinking), the process is to solve the problem of the steps, process-oriented design is like a well-designed pipeline, consider when to deal with what things.
The advantage is: greatly reduces the complexity of the program;
Disadvantage is: poor scalability, change code trouble;
Application scenario: Once you have completed a very rarely changed scenario, the notable examples are Linux kernel, git, and Apache HTTP server.
Object-oriented program design is the core of the object (God-like thinking), to understand what the object is, we must regard themselves as God, God in the eyes of the world exists in all things are objects, not exist can also be created. Object-oriented programming good for example, to design a journey to the east, the Tathagata to solve the problem is to pass the scriptures to the Eastern Earth Datang, the Tathagata thought to solve this problem requires four people: Tang's monk, Sha Monk, Pig Eight commandments, Monkey King, everyone has their own characteristics and skills (this is the concept of objects, Characteristics and skills corresponding to the object's data properties and method properties, but this is not fun, so the Tathagata arranged a group of ghosts and goblins, in order to prevent the four of them in the road of learning to be killed, and arranged a group of immortal escort, these are objects. Then the beginning of the lessons, master and disciple four people with ghosts and goblins to interact until the final canon. The Tathagata does not control the four people follow what process to take.
Object-oriented program design
Advantages: It solves the extensibility of the program. A single modification of an object is immediately reflected in the entire system, such as the character of a character parameter in the game and the ability to modify it easily.
Cons: Poor controllability, inability to process-oriented programming pipeline can be very accurate prediction of the problem of the processing process and results, the object-oriented program once started by the interaction between the object to solve the problem, can not predict the final result. So we often see a game person A parameter modification is likely to lead to the skill of the bug, a knife to kill 3 people, the game is out of balance.
Application scenario: frequently changing requirements of the software, the general needs of the changes are concentrated in the user layer, Internet applications, enterprise internal software, games, etc. are object-oriented programming is a good place to play.
Object-oriented programming is not all. For a software quality, object-oriented programming is just to solve extensibility.
Two. Classes and objects 1. Defining
Everything in Python is an object, and Python3 unifies the concept of classes and types, which are classes.
Based on object-oriented design a game: League of Legends, each player to choose a hero, each hero has its own characteristics and skills, characteristics that are data attributes, skill is the method of attributes, characteristics and skills of the combination of an object.
Extracting similar parts from a set of objects is a combination of features and skills that all objects of a class have.
In Python, a variable represents a feature, a function represents a skill, and a class is a combination of a variable and a function, and an object is a combination of a variable and a method (a function that points to a class).
2. Declarations of Classes
Declaring a class in Python is similar to declaring a function
' Class class name: ' Class ' document String ' body ' #我们创建一个类class Data: Pass
- Category: New class and Classic class
1. Only in the Python2 want $ The new class and the classic class, the unification in the Python3 is the new class
2. The biggest difference between the new class and the classic class declaration is that all modern classes must inherit at least one parent class
3. All classes do not explicitly declare the parent class, there is a default inheritance object parent class (speaking of inheritance will say, remember first)
Distinction in Python2 Classic class: Class Name: Pass New class: Class name (parent Class): Pass in Python3, both of these definitions are all new-style classes
Cases:
Class Garen: #定义英雄盖伦的类, different players can use it to instantiate their own heroes; The camp of camp= ' Demacia ' #所有玩家的英雄 (Galen) is Demacia; Def attack (Self,enemy): #普通攻击技能, Enemy is the enemy; Enemy.life_value-=self.aggressivity #根据自己的攻击力, attack the enemy and lose the enemy's health.
3. Two uses of the class
- A reference to a class property
Class Garen: #定义英雄盖伦的类, different players can use it to instantiate their own heroes; The camp of camp= ' Demacia ' #所有玩家的英雄 (Galen) is Demacia; Def attack (Self,enemy): #普通攻击技能, Enemy is the enemy; Enemy.life_value-=self.aggressivity #根据自己的攻击力, attack the enemy and lose the enemy's health. Print (Garen.camp) #引用类的数据属性, which shares print (garen.attack) #引用类的函数属性 with all objects/instances, which also shares the print (garen.__dict__) #查看类的属性字典, Or say namespace # garen.name= ' Garen ') #增加属性 # del Garen.name #删除属性
"""
Output:
Demacia<function Garen.attack at 0x106acd400>{‘__doc__': None,‘Attack': <function garen.attack at 0x106acd400>‘__module__‘:‘__main__‘,‘__weakref__': <attribute '__weakref__' of 'garen' objects>, 'Camp ': 'demacia ', '__dict__': <attribute '__dict__' of 'Garen ' Objects>}
"""
The class name parentheses are instantiated, which automatically triggers the operation of the __INIT__ function, which can be used to customize the characteristics of each instance.
Class Garen: #定义英雄盖伦的类, different players can use it to instantiate their own heroes; The camp of camp= ' Demacia ' #所有玩家的英雄 (Galen) is Demacia; def __init__ (self,nickname,aggressivity=58,life_value=455): #英雄的初始攻击力58 ...; Self.nickname=nickname #为自己的盖伦起个别名; Self.aggressivity=aggressivity #英雄都有自己的攻击力; Self.life_value=life_value #英雄都有自己的生命值; Def attack (Self,enemy): #普通攻击技能, Enemy is the enemy; Enemy.life_value-=self.aggressivity #根据自己的攻击力, attack the enemy and lose the enemy's health. G1=garen (' Bush lun ') #就是在执行Garen. __init__ (G1, ' Bush Lun '), then execute __init__ code g1.nickname= ' Bush lun ' and other print (G1) print (G1.nickname) "" Output: <__main__. Garen object at 0x10ee26e10> Bush lun "" "
Note: The function of self is to automatically pass the object/instance itself to the first parameter of the __init__ when instantiated, and it can be any name
Add:
A: Where do the properties of the class we define are stored? There are two ways to view 1.dir (class name): A list of names is found 2. Class name. __dict__: A dictionary is found, key is the property name, value is the property value two: Special Class attribute class name. __name__# class Name (String) class name. __doc__# Class name of the document String class. The first parent class of the __base__# class (Speaking of inheritance) class name. A tuple of all the parent classes of the __bases__# class (Speaking of inheritance) class name. The class name of the dictionary attribute of the __dict__# class. The __module__# class defines the module class name. Class for __class__# instances (in modern class only)
4. Creation and reference of objects
- An object is an example of a class that actually exists, that is, the instantiation of a class.
G1=garen (' Bush lun ') #实例化类就是对象print (G1) print (g1.nickname) print (Type (G1)) #查看g1的类型就是类Garenprint (Isinstance (G1,garen)) # G1 is the example of Garen "" "<__main__. Garen object at 0x108d55dd8> Bush <class ' __main__. Garen ' >true ' "" "
- Object has only one reference: Property Reference
The object/instance itself actually has only data properties
Class Garen: #定义英雄盖伦的类, different players can use it to instantiate their own heroes; The camp of camp= ' Demacia ' #所有玩家的英雄 (Galen) is Demacia; def __init__ (self,nickname,aggressivity=58,life_value=455): #英雄的初始攻击力58 ...; Self.nickname=nickname #为自己的盖伦起个别名; Self.aggressivity=aggressivity #英雄都有自己的攻击力; Self.life_value=life_value #英雄都有自己的生命值; Def attack (Self,enemy): #普通攻击技能, Enemy is the enemy; Enemy.life_value-=self.aggressivity #根据自己的攻击力, attack the enemy and lose the enemy's health. G1=garen (' Bush lun ') #类的实例化就是对象print (g1.nickname) #对象的属性引用print (g1.aggressivity) print (G1.life_value) "" "Bush Lun 58455" "
Add:
The object/instance itself has only data properties, but the Python class mechanism binds the function of the class to the object, called the object's method, or is called a binding method, the binding method uniquely binds an object, the method of the same class is bound to a different object, a different method, and the memory address is not the same.
Print (G1.attack) #对象的绑定方法print (garen.attack) #对象的绑定方法attack本质就是调用类的函数attack的功能, which is a binding relationship "" "
Output: <bound method Garen.attack of <__main__. Garen object at 0x10809ee10>><function garen.attack at 0x1081e3488> "" "
The special thing about object binding methods is that Obj.func () passes obj to the first argument of Func.
5. Interaction between objects
Follow the Garen class and create a riven class to attack Galen with Rui Wen and complete object interaction
Class Garen: #定义英雄盖伦的类, different players can use it to instantiate their own heroes; The camp of camp= ' Demacia ' #所有玩家的英雄 (Galen) is Demacia; def __init__ (self,nickname,aggressivity=58,life_value=455): #英雄的初始攻击力58 ...; Self.nickname=nickname #为自己的盖伦起个别名; Self.aggressivity=aggressivity #英雄都有自己的攻击力; Self.life_value=life_value #英雄都有自己的生命值; Def attack (Self,enemy): #普通攻击技能, Enemy is the enemy; Enemy.life_value-=self.aggressivity #根据自己的攻击力, attacking enemies with the enemy's health to reduce damage. Class riven:camp= ' Noxus ' #所有玩家的英雄 (Rui Wen) of the camp are Noxus; def __init__ (self,nickname,aggressivity=54,life_value=414): #英雄的初始攻击力54; Self.nickname=nickname #为自己的锐雯起个别名; Self.aggressivity=aggressivity #英雄都有自己的攻击力; Self.life_value=life_value #英雄都有自己的生命值; Def attack (Self,enemy): #普通攻击技能, Enemy is the enemy; Enemy.life_value-=self.aggressivity #根据自己的攻击力, attacking enemies with the enemy's health to reduce damage. G1=garen (' Galen ') #就是在执行Garen. __init__ (G1, ' Bush Lun '), then executes __init__ code g1.nickname= ' Bush lun ' etc r1=riven (' Rui Wen ') print (g1.life_ Value) print (R1.attack (G1)) #对象交互, Rui Wen attack Galen print (G1.life_value) "" "Output: 455None401 "" " 6. Class namespace and Object/instance namespace
Creating a class creates a namespace for a class that stores all the names defined in the class, which are called properties of the class.
Class has two properties: Data Properties and Function properties
Where the data properties of a class are shared to all objects
Variables defined inside a class are common to all objects and have the same ID.
Print (R1.camp) #本质就是在引用类的camp属性, both ID print (ID (riven.camp)) "" "
Output: 44827765124482776512 "" "
The function properties of a class are bound to all objects:
A function defined inside a class, bound to all objects, is used for the object, and Obj.func () will use obj itself as the first argument.
R1.attack is performing the function of Riven.attack, Python's class mechanism will riven function properties attack binding to r1,r1 equivalent to get a pointer to riven class attack function, R1.attack () The first parameter that will pass R1 to attack
Print (ID (r1.attack)) print (ID (riven.attack)) "" "Output: 43728501844374779288" ""
Note:
Creating an object/instance creates an object/instance namespace that holds the name of the object/instance, called the object/instance property
In the Obj.name will first find the name in Obj's own namespace, can not find the class to find, the class can not find the parent class ... Throw an exception if you can't find it at the end
Print (g1.x) #先从g1. __dict__, can not find garen.__dict__, find will error
Four. Inheritance and derivation 1. The meaning of inheritance
Inheritance is a way to create a new class, in Python, a new class can inherit one or more parent classes, which can be called a base class or a superclass, and a new class is called a derived class or subclass.
- Single inheritance and multiple inheritance
Class ParentClass1: #定义父类 passclass ParentClass2: #定义父类 passclass SubClass1 (PARENTCLASS1): #单继承, The base class is ParentClass1, and the derived class is subclass Passclass SubClass2 (parentclass1,parentclass2): #python支持多继承, separating multiple inherited classes with commas Pass
__base__ only view the first subclass inherited from left to right, __bases__ is to view all inherited parent classes
Print (subclass2.__base__) print (subclass2.__bases__) "" "Output: <class ' __main__. ParentClass1 ' > (<class ' __main__. ParentClass1 ';, <class ' __main__. ParentClass2 ' >) "" "
If you do not specify a base class, the Python class inherits the object class by default, object is the base class for all Python classes, and it provides implementations of some common methods, such as __str__.
Print (parentclass1.__base__) "" "Output: <class ' object ' >" ""
7.
Object-oriented Python