First, reflection
Say reflection before the introduction of the __import__ method, this and import imported module another way
Import Commons__import__('commons' )
If it is a multilayer import:
from Import __import__(' list.text.commons', fromlist=true) # If you do not add fromlist=true, only the list directory will be imported
Reflection has the idea that 4 built-in functions are: GetAttr, hasattr, SetAttr, delattr get members, check members, set members, delete members The following is a first look at the example:
Class Foo (object): def __init__ (self): self.name = ' abc ' def func: return ' OK ' obj = Foo () # Get member ret = getattr (obj, ' func ') #获取的是个对象r = RET () print (r) #检查成员ret = hasattr (obj, ' func ') #因为有func方法所以返回Trueprint (ret) # Set member print (obj.name) #设置之前为: Abcret = setattr (obj, ' name ', +) print (obj.name) #设置之后为: 19# Delete member print (obj.name) #abcdelattr (obj, ' name ') print (obj.name) #报错
For reflection subsections:
1. Import the module as a string. 2. To manipulate its members in the form of a string into an object (a module)
Example: A routing system based on reflection to implement a class web framework
Implementation of the idea: Specify the user input format module name/function name through the form of __import__ import module and through hasattr and getattr check and get function return value.
second, object-oriented
Oop, object-oriented programming treats computer programs as a set of objects, and each object can receive messages from other objects and process them, and the execution of a computer program is a series of messages passing between objects.
Syntax format see:
The keyword class and the function def are the same. The class name is usually the first word in uppercase, and after the definition class it is possible to create an instance of the class plus () equivalent to creating an example of a class obj
- def Bar (self) where self is the formal parameter
- Same as the memory address of the instantiated object obj
The three main characteristics of a class: encapsulation, inheritance, polymorphism
1. Encapsulation
An important feature of object-oriented programming is data encapsulation. For example:
class Foo: def fetch (self): Print (self.beckend) # Self directly in the object to take value ='www.baidu.com' # Wrap The beckend inside the object Obj.fetch ()
non-mainstream usage
classFoo:" "Construction Method" " def __init__(SELF,BK): Self.backend= BK#encapsulates the parameters of the Obj object in the Init method deffetch (self):Print(self.backend)defAdd (self):Print(self.backend) obj= Foo ('www.xxx.com') Obj.fetch () Obj.add ()
Mainstream usage
Through the code we see __init__: called the construction method, it is important to note that the first parameter of __init__ is always self, which represents the instance itself
The meaning of encapsulation: When a method of the same type has the same parameters, it can be encapsulated directly into the object to reduce the amount of code.
Use a scenario to treat a class as a template, create multiple objects, and encapsulate the data in an object differently.
2. Inheritance
When we define a class, we can inherit from an existing class, the new class is called a subclass (subclass), and the inherited class is called the base class, the parent class, or the superclass (base class, Super Class), and there are a few things to note:
- Inherit the class name of the parent class to be added to the child class
- Methods for subclasses and parent classes, and methods for child classes are preferred
- Python can inherit multiple classes C#,java can not inherit more
- If you inherit multiple classes, the inheritance order is from left to right
For example, the following example:
classAnimals:defChi (self):Print(self.) Name +'Eat') defHe (self):Print(self.) Name +'Drink')classDog (Animals):def __init__(self,name): self. Name=namedefJiao (self):Print(self.) Name +'called') Xxoo=dog ('some xxx') Xxoo.chi () xxoo.he () Xxoo.jiao ( )
Inheriting Instances
classAnimals:defChi (self):Print(self.) Name +'Eat') defHe (self):Print(self.) Name +'Drink')classUncle:defdu (self):Print(self.) Name +'Bet')classDog (animals,uncle):def __init__(self,name): self. Name=Namexxoo= Dog ('some xxx') Xxoo.chi () Xxoo.du ()
Multiple Inheritance
The inheritance order requires attention such as e-Inheritance (c,d)-->c Inheritance (A)-->d inheritance (B) such as (Python3):
classA:defF1 (self):Print('A')classB:deff (self):Print('B')classC (A):deff (self):Print('C')classD (B):defF1 (self):Print('D')classE (c,d):deff (self):Print('E') AA=E () aa.f1 ()
the lookup order of the class
The second lookup order: E Inheritance (c,d)-->c Inheritance (A), D Inheritance (B)-->a and B both inherit (Boos), the lookup order is as follows:
classBoos:defF1 (self):Print('Boos')classA (Boos):deff (self):Print('A')classB (Boos):deff (self):Print('B')classC (A):deff (self):Print('C')classD (B):defF1 (self):Print('D')classE (c,d):deff (self):Print('E') AA=E () aa.f1 ()
Lookup Order
3. polymorphic
That is, many forms ....
Add:
about how inheritance executes the construction method of the parent class. There are two ways to do this:
classAnnimal:def __init__(self):Print('the construction method of Annimal') Self.ty='Animal'classCat (annimal):def __init__(self):Print('how to construct cat') SELF.N='Cat'Super (Cat, self).__init__()#recommended for this #annimal.__init__ (self) #第二种方式c = Cat ()
To perform a parent class construction method
Find the source of the process (Self.xxxx (), starting from the bottom of the search)
Third, Members
There are static fields, static methods, class methods, attributes, common fields, common methods,
Class Provice: #静态字段 country = ' China ' def __init__ (self,name): #普通字段 self.name = name #普通方法 def Show (self): print (' show ') @staticmethod #静态方法 def XO (ARG): Print (' XO ') print (ARG) @classmethod #类方法, you must have a CLS parameter: Automatically passing in the class name def xxoo (CLS): print (' Xxoo ', CLS) def start (self): Print (' start ') @property #特性 def end (self): print (' End ') @end. Setter def end (self,values ): print (values) Self.name = values #也可以更改内存里的值Provice. Country #类访问静态字段Provice. XO (' Alex ') # Class Access static method Provice.xxoo () #访问类方法 # Get the attribute value obj = provice (' Alex ') obj.end# set the attribute value obj1= provice (' Alex ') obj1.end= ' 123 ' Print ( Obj1.name) #普通方法obj1 = Provice (' Alex ') obj1.show () #普通字段obj1 = Provice (' Alex ') print (obj1.name)
Member section:
- themselves to visit their own members, in addition to the methods in the class
Access by class: Static fields, static methods, class methods
Access by object: Normal fields, common methods, features
Static fields: The existence of a static field in a class means that the repeated data in the object only holds a static method in the class: No self can pass arguments, and when called, it is necessary to pass in parameters, meaning: You do not need to create objects, you can access this method, for the class of the class method: You must have a CLS parameter that automatically passes in the class name attribute object Invocation, cannot add parameters, executes without parentheses, and stores the ordinary method in the object. The common method is that if you want to be called, you need to create self, which is the object
the significance of the existence of the MembersIv. member Modifiers
Public members: Accessible anywhere
Private Member: Accessible only within the class, defined as named, with the first two characters underlined, such as "__test"
class Person (object): country = ' China ' #静态字段, belongs to the public member __planet = ' Earth ' #静态字段, belongs to the private member def __init_ _ (Self,name): print ' person build self.name ' self.name = name def say (self): print ' The planet is%s '% Person.__planet #在类的内部访问私有静态字段 p1 = person (' Nothing ') P1.say () print p1.country #访问公有静态字段print p1.__ Planet #访问私有静态字段 # Execution Result: Person build self.namethe Planet is Earth #在类的内部可以访问 Print P1.__planetchina #外部可以访问公有静态字段AttributeError: ' Person ' object with no attribute ' __planet ' #外部无法访问私有静态字段
Subsection: A private member can only be used inside a class, others cannot use a subclass that includes inheritance
Special members of the class:
__doc__ represents the class description information __module__ represents the current operation of the object in that module __class__ represents the current operation of the object's class is what __init__ constructor method, when the object is created by the class, automatically trigger execution the __call__ object is appended with parentheses to trigger execution. __dict__ all members of the class or object __str__ if the __str__ method is defined in a class, the return value of the method is output by default when the object is printed. __init__ constructs a method that automatically triggers execution __setitem__,__getitem__,__delitem__ for index operations, such as dictionaries, when an object is created through a class. Get, set, delete data, respectively
V. Exception handling
An exception is an event that occurs during program execution and affects the normal execution of the program.
In general, an exception occurs when Python does not handle the program properly.
The exception is a Python object that represents an error.
When a Python script exception occurs, we need to capture and process it, or the program terminates execution.
Grammar:
try:< Statement > #运行别的代码except < name >:< statement > #如果在try部份引发了 ' name ' exception except < name >,< data >:< Statement > #如果引发了 ' name ' exception, get additional data else:< statement > #如果没有异常发生finally: xxxx
The standard exceptions are:
Baseexception the base class of all exceptions Systemexit interpreter requests to exit Keyboardinterrupt user interrupt Execution (usually input ^c) Exception General error base class Stopiteration iterator no more values Generatorexit generator (generator) An exception occurred to notify the base class of all built-in standard exceptions that exited StandardError arithmeticerror all numeric calculation errors for base class Floatingpointerror floating-point calculation error overflowerror numeric operation exceeded maximum limit Zerodivisioner Ror except (or modulo) 0 (all data types) Assertionerror Assertion statement failed Attributeerror object does not have this property Eoferror no built-in input, reached EOF Flag EnvironmentError Operating system error base class IOError input/output operation failed OSError operating system error Windowserror system call failed Importerror Import module/ Object failed lookuperror Invalid data query base class Indexerror sequence does not have this index (index) in Keyerror mapping does not have this key Memoryerror memory overflow error (not fatal for Python interpreter) Nameerror non-declaration/initialization Object (no attribute) Unboundlocalerror access to uninitialized local variable referenceerror weak reference (Weak reference) An attempt was made to access a garbage-collected object RuntimeError general run-time error notimplementederror a method that has not yet been implemented Syntaxerrorpython Syntax error Indentationerror indentation error Taberrortab mixed with spaces Systemerror General interpreter system error TypeError an operation that is not valid for type ValueError passed in an invalid parameter Unicodeerrorunicode related error Unicodedecodeerrorunicode Error Unicodeencodeerrorunicode encoding when decoding error Unicodetranslateerrorunicode The base class of the error warning warning on conversion deprecationwarning warning about deprecated features futurewarning warning about constructing future semantics overflowwarning old about automaticElevated to long pendingdeprecationwarning warning runtimewarning suspicious runtime behavior for attributes that will be discarded (runtime behavior) Warning syntaxwarning suspicious syntax warning userwarning user code generated warning
The reflection and function of the Python series