Object-Oriented Fundamentals |
1. What is object-oriented programming?
-Previously used functions
-Class + Object
2. What is a class and what is an object and what does it matter?
class class: def function 1 (): Pass def function 2 (): Pass # obj is an object that instantiates the process obj = class () obj. function 1 ()
========== object-oriented bad ============
========== function Programming Good ==============
-Sometimes, function programming can be implemented? More trouble.
-Object-oriented is very simple to implement.
3. When is an object-oriented application?
-1. When multiple functions have common parameters
-2. Create something based on a template
-3. Link server, execute command, close
Note: Object-oriented, you can make more changes to modify the requirements.
4.self is the object that invokes the current method.
-The function (method) is stored in the class.
-The field is saved under Object memory.
5. Usage scenarios for static fields.
-Each field you create has a common value and can be set as a static field.
Member properties
class Foo: def __init__ (self,name): # normal field, property =" China "
Global Properties
class Foo: # static fields, public properties " China "def__init__= name
6. Object-oriented three major features, inheritance, encapsulation, polymorphism.
Packaging:
-In-Class encapsulation: Fields, methods
-The value of the normal field is encapsulated in the object:
Example
classF1:def __init__(self,n): self. N=NPrint('F1') classF2:def __init__(SELF,ARG1): SELF.A=arg1Print('F2') classF3:def __init__(SELF,ARG2): self.b=arg2Print('F3') O1= F1 ('Alex') O2=F2 (O1) O3=F3 (O2)########### Output alex:o3.b.a.n############O1 = F1 (' Alex ')#O2 = F2 (O1)#O3 = F3 (O2)#print (O3.B.A.N)#Execution Results#Alex#Note: O3 contains O2 containing O1 containing n assignments for Alex.
Inherited:
Example:
Find the result: corresponding inheritance.
classF1:def __init__(self):Print('F1') defA1 (self):Print('F1A1') defA2 (self):Print('f1a2') classF2 (F1):def __init__(self):Print('F2') defA1 (self):Print('F2A1') defA2 (self): self.a2 ()Print('f2a2') classF3 (F2):def __init__(self):Print('F3') #def a1 (self):#print (' f3a1 ') defA2 (self):Print('F3A1') obj=F3 () obj.a1 ( )
Polymorphic:
-Python: Default support polymorphism, no type limit
-Polymorphic: Multiple forms.
7. Fields and Methods
Field:
Normal field (saved in object)
Static fields (saved in class)
Method:
Normal method (save in class, caller object, at least one self parameter)
class F1: ... def A1 (self): Print == A1 ()# Note: obj object memory is not stored in the data and consumes memory.
Static methods (stored in a class, caller class, without creating an object, can have any parameter):
class F1: @staticmethod def A1 (): print(self.name) f1.a1 () # Note: equivalent to function @staticmethod.
Python Object-Oriented basics