I. THE CONCEPT OF POLYMORPHISM
1. What is polymorphism?
A thing has a variety of forms, that is, to face the various states of the object.
Official Interpretation: Multiple different classes of objects can respond to the same method and produce different results
It is emphasized that polymorphism is not a special grammar, but a state and characteristic, that is, multiple objects have the same usage.
2. Advantages
1. Increased flexibility of procedures
2. Increase the extensibility of the program
3. For users, the difficulty of use is correct.
3. Realizing polymorphism
Interfaces, Abstract classes, duck types can all write polymorphic code.
The simplest is the duck type.
4. Examples:
1.How to manage chickens, ducks and geese most conveniently? class Chicken: def speak(self): print('Hao Ji') def spawn(self): print('Laying eggs') class Duck: def speak(self): print('Gagaga') def spawn(self): print('Laying duck eggs') class Er: def speak(self): print('Goose, goose and goose') def spawn(self): print('Chardin') j = Chicken() y = duck() e = Er() def mange(obj): obj.spawn() mange(j) mange(y) mange(e) //Example analysis: chickens, ducks and geese are all animals. They all have the skill of laying eggs, so they can define a unified interface. //To use def mange(obj): obj.spawn() 2.Another example is: a = 10 b = '10' c = [10] print(type(a)) print(type(b)) print(type(c)) #a,b,c They all have their own types. # That's what they all have in common.
2. OPP-related built-in functions
1.inistance
Determine whether an object is an instance
Parametric 1: The object to be judged
Parametric 2: Types to be judged
Examples:
def add_num(a,b): # here a,b For parameter one if isinstance(a,int) and isinstance(b,int): # here a,b Parametric 2 return a+b return None print(add_num(20,10)) # Print result: 30
2.issubclass
Determine whether a class is a subclass of another class
Parametric 1: Subclass
Parametric 2: Parent class
Examples:
class Animal: def eat(self): print('Animals can eat') class Dog(Animal): def eat(self): print('Dogs eat bones') class Tree: def light(self): print('Plant photosynthesis') dog = Dog() tree = Tree() def manage(obj): if issubclass(type(obj),Animal): # Determine whether this class is Animal Subclass, if it is, prints the content of the object, otherwise returns the result: not an animal obj.eat() else: print('Not an animal.') manage(dog) # Dogs eat bones manage(tree) # Not an animal.
3. Magic Functions in Classes
1.str
Formatting method: Printing this kind of object outside is called
Formatting the external direct printing of the string representation results of this class of objects
str converts an object to a string, and the result of the conversion is the return value of the function.
Scenario: We can use this function to define the object in print format.
class A: def __init__(self,name,age): self.name = name self.age = age def __str__(self): return 'my name is %s,my age is %s'%(self.name,self.age) a = A('jack',18) print(a) # Print results: my name is jack,my age is 18
2.del
Deconstruction: Called the moment an object is consumed, something can be done before it is consumed
del is called when the object represented by self is consumed, or some resources are persisted (saved to file database)
Execution timing: Delete objects manually and execute immediately, or automatically when the program runs
Use scenarios: When your object is in use, open resources that do not belong to the interpreter
Examples:
class FileTool: """This class is used to simplify the reading and writing of files. """ def __init__(self,path): self.file = open(path,"rt",encoding="utf-8") self.a = 100 def read(self): return self.file.read() # One thing can be determined here.,This object is definitely not used, so you can safely close the question file. def __del__(self): self.file.close() tool = FileTool("a.txt") print(tool.read())
3.call
Execution timing: Automatically executes when an object is called (that is, the object is bracketed)
class A: def __call__(self, *args, **kwargs): print("call run") # print(args) print(kwargs) a = A() a(1,a=100)
4.slots
This property is a class property used to optimize object memory usage
Principle of optimization: Fixed the original number of attributes
Such an interpreter would not create a namespace for this object, so dict would not exist.
So as to achieve the effect of reducing memory overhead
If slots occur in a class, the object of that class will not be able to add new attributes.
class Person: __slots__ = ["name"] def __init__(self,name): self.name = name p = Person("jck") # View memory usage # print(sys.getsizeof(p)) # p.age = 20 # Cannot add # dict Period # print(p.__dict__)
5.getattr setattr delattr
getattr accesses attributes with points if attributes do not exist
When setattr sets properties with points
delattr executes these functions when deleting attributes with del objects. Attributes reflect how the python interpreter implements point-to-point access to attributes getattribute s, which are also used to obtain attributes.
If a getattribute exists, the function is executed first, if no attribute is obtained, the getattr function is continued to be called, and if it is obtained, it is returned directly.
6. [] Real Principles
getitem setitem delitem
Any symbol will be interpreted as a special meaning by the interpreter; for example.
getitem: Executed when attributes are retrieved with middle brackets
setitem: executed when setting properties with middle brackets
delitem: Executed when attributes are deleted with middle brackets
Operator overloading
When we use a symbol, the python interpreter defines a meaning for the symbol and calls the corresponding processing function. When we need to define the comparison rules of objects, we can cover a series of methods in subclasses that are greater than or equal to each other.
Examples:
class Student: def __init__(self,name,age,height): self.name = name self.age = age self.height = height # def __gt__(self, other): # _ gt_ is greater than sign; _lt_ is less than sign (only one is needed) # # return self.height < other.height # self is itself, stu1. other means stu2. def __eq__(self, other): return self.height == other.height # Return based on the bottom print True perhaps False stu1 = Student('jack',18,178) stu2 = Student('lucy',17,178) print(stu1) print(stu2) #print(stu1 > stu2) # More than comparison (or less than comparison) print(stu1 == stu2) # Equivalent to comparisonIn the above code,other Refers to another person who participates in the comparison.,
Bigger than and less than one can be achieved.,Symbols automatically exchange the positions of two objects if they are interpreted differently
Iterator Protocol
Iterator is an object with _iter_ and _next_ we can add these two methods to make the object an iterator
class MyIRange: def __init__(self,start,end,step): # step Represents step size self.start = start self.end = end self.step = step def __iter__(self): return self def __next__(self): a = self.start self.start += self.step if a < self.end: return a else: raise StopIteration # Returns an exception for i in MyIRange(1,10,2): print(i)
VI. Management of Upper Writing
Write above: context
This concept belongs to Linguistics and refers to the meaning of a paragraph, referring to the current situation, that is, the context.
In python, context can be understood as a code interval, a range, such as a file opened with open, that is valid only in this context
Two methods are involved:
1.enter
Represents entry context
2.exit
Represents an exit context
class MyOpen(object): def __init__(self,path): self.path = path # Route def __enter__(self): self.file = open(self.path) # Open the file print("enter.....") return self def __exit__(self, exc_type, exc_val, exc_tb): print("exit...") # print(exc_type,exc_val,exc_tb) self.file.close() # Close files return True with MyOpen('a.txt') as m: print(m.file.read()) //When the with statement is executed, enter is executed first, exit is executed when the code is executed, or exit is executed immediately when the code encounters an exception, and an error message containing the type of error, error information, error tracking information is passed in. enter Functions should return the object itself exit Functions can have return values,Is a bool type,Used to indicate whether an exception has been handled,Exceptions are useful only in context if True That means,Exceptions and handled False,Exceptions not handled,Program will interrupt error reporting