38 Environment Manager:
Ø classes that have __enter__ and __exit__ methods are called environment managers
Ø an object that can be managed with a with statement must be an environment manager
Ø__ENTER__ will be invoked when entering the With statement and return objects managed by the as variable
Ø__EXIT__ will be invoked when leaving with, and can use parameters to determine whether an exception occurred while leaving the with statement, and to do the appropriate processing 38.1 example
Class Cooker: def open_gas (self): Print ("Open gas") def close_gas (self): Print ("Turn off gas") def dowork (self): Print ("Making sesame cake") def __enter__ (self):
Self.open_gas ()
Value of the exception type |
|
return self
def __exit__ (self, exc_type, Exc_value, EXC_TB):
Self.close_gas ()If Exc_type is None: Print ("Normal Leave") Else Print ("Exception exit")
With cooker () as C: C.dowork () |
39 Coding Specification
PEP8 Coding Specification
Create multiple objects and have their own namespaces so that there is no conflict
Inheritance, encapsulation, polymorphism 40 inheritance (inheritance) and derivation (derived) 40.1 purposes of inheritance
Inheritance for the purpose of continuing the old function
The purpose of the derivation is to add a new function on top of the old function 40.2 function
With the inheritance derivation mechanism, some common functions can be loaded on the base class, code sharing is implemented, and the original function is changed without changing the superclass code.
Base class (base class)/superclass (super Class)/parent (Father Class)
Derived class (DerivedClass)/subclass (Child Class) 40.3 single inheritance Syntax:
Class name (super Class name):
······· 40.4 Inheritance Description:
Any class inherits directly or indirectly from the object class
Object class is the superclass 40.5 __base__ property of all classes
Role:
base class (Instance of Class) used to record this class
Import Human Class Student (human. Human): Pass S1 = Student () Print (s1.__class__.__base__ ()) # Print (s1.__class__.__base__) # <class ' Human. Human ' > Print (s1.__class__.__base__.__base__) # <class ' object ' > Print (student.__base__) # <class ' Human. Human ' > Print (student.__base__.__base__) # <class ' object ' > Print (object.__base__) # None |
40.6 overwrite override (rewrite overwrite)
What is overlay
Overwrite is a class that has an inheritance relationship that implements a method with the same name as the base class, and when it is invoked by a subclass instance, it actually calls the version overridden in the subclass, which is called overriding
The subclass object shows how the base class method is invoked
The base class name. Method Name (object, parameter) #先调用子类, if no more base class is found
Instance. Method Name (parameter) #此时实例调用的是子类自己的方法 (such as the method name in the fruit Class) 40.7 Super function
Øsuper (Type,obj) Returns an instance of the binding superclass (requires obj to be an instance of type)
Øsuper () Returns an instance of the binding superclass, equivalent to (class, the first parameter of the instance method), which must be used to 40.7.1 the function within the method:
Returns an instance of the binding superclass, using an instance of the superclass to invoke its own method 40.7.2 sample
Class A: def hello (slef): Print ("Hello (self)" in Class A) Class B (A): def hello (self): Print ("Hello for Type B")
Base = B () Base.hello () # b kind of Hello Super (B, base). Hello (self) in Class A is equivalent to B.__base__.hello (base) #类名. Method name (instance, parameters) |
| Class A: def hello (slef): & nbsp; Print (hello (self) in class A) Class B (a): def hello (self): print ("Hello for Type B") def Super_hello (self): Self.hello () Super (b,self). Hello () super (). Hello () Base = B () Base.hello () # B kind of Hello Super (B, base). Hello () # a Class (self) is equivalent to B.__base__.hello (base) Base.super_hello () Type B Hello Hello (self) in the A class Type B Hello Hello (self) in the A class The Hello (self) | in Class A
41 with functions of the class
Issubclass (CLS, class, or class tuple)
Determines whether a class inherits from other classes, returns True if such CLS is a derived class in Class (Class) or tuple, or false
Class A: Pass Class B (A): Pass Class C (B): Pass Class D (C): Pass Print (Issubclass (c,a)) #True Print (Issubclass (d,b)) # True Print (Issubclass (d,a)) #True Print (Issubclass (bool,int)) #True Print (Issubclass (bool,float)) #False |
42 shows the constructor method that invokes the base class:
def__init__ (self,) :
············
Example Class Human (object): "" "DocString for ClassName" "" def __init__ (self, Name, age): Self.name = Name Self.age = Age def infos (self): Print (' Name: ', Self.name, ' Age: ', self.age) Class Student (Human):
Note: There is no self, there is a sequence |
|
def __init__ (self, name, age, score):Super (Student, self). __INIT__ (name, age) # self.name = Name # Self.age = Age Self.score = Score def infos (self): Print ("name", Self.name, ' age ', Self.age, ' score: ', Self.score) H1 = Human ("Zhang Shan", 18) H1.infos () S1 = Student (' Xiao Ling ', 20, 99) S1.infos () Name: Zhang Shan age:18 Name Xiao Ling age score:99 |
43 polymorphic polymorphic
43.1 Definition
It literally means ' multiple states '
Polymorphism is a method of invoking a base class object in a class that has an inheritance/derivation relationship, and the actual ability to invoke a subclass's coverage method
The method of polymorphic invocation is related to the object and is not related to the type
Class Shape: def draw (self): Self.drawself () Class Point (Shape): def drawself (self): Print ("❀ bird") Class Circle (point): def drawself (self): Print ("Draw a Circle") Shape = Point () Shape.draw () #❀ a bird Shape = Circle () Shape.draw () #画个圆 |
44 characteristics of object-oriented thought:
1 package
2 Inheritance (derivation)
3 polymorphic (because of this feature, the list can be stored in multiple data types) 45 Encapsulation: Enclosure 45.1 function
Encapsulation refers to the implementation details of hidden classes, so that users do not care about these details
Note: Python encapsulation is a fake (analog) encapsulation of 45.2 private instance variables and methods:
Python class, with a double underscore ' __ ', with a character that does not end with a double underline as a private member
Private members are divided into:
Private properties and Private methods
Private members cannot be accessed outside of subclasses and classes
Class A: def __init__ (self, args): Self.__p = args def ShowA (self): Print ("Self.__p:", self.__p)
A = a (100) A.showa () Print (a.__p) Execution results self.__p:100 Traceback (most recent call last): File "enclosure.py", line, in <module> Print (a.__p) Attributeerror: ' A ' object has no attribute ' __p ' |
Class A: def __init__ (self, args): Self.__p = args def ShowA (self): Return self.__p
A = a (100) Print (A.showa ()) #100 can get the value |
more than 46 inherited multiple inheritance
Multiple inheritance refers to a subclass inheriting two or more base classes with more than 46.1 inherited syntax:
Class name (superclass Name 1, super class name 2 ):
···········
Class Car: def run (self, speed): Print ("Car with", speed, ' km/h speed Drive ') Class Plane: Def fly (self, height): Print ("At elevation", height, ' flight over meters ') Class Planecar (Car, Plane): "' Planecar class inherits airplanes and cars at the same time No pass, no writing. ''' PL = Planecar () Pl.fly (20000) #在海拔 flight over 20000 meters Pl.run (+) #汽车以 km/h speed |
46.2 defects of multiple inheritance
Problem with identifier conflicts
Be cautious about using multiple inheritance
Class A: def __init__ (self): Self.name = ' A ' Class B (object): "" "DocString for B" "" def __init__ (self): Self.name = ' B ' Class AB (A, B): #换成 (b,a) The result is B def infos (self): Print (Self.name) AB = AB () Ab.infos () #A |