I learned some before, but now I forget all about it. When I had time, I looked again and made the following records

There is a foundation of object-oriented language. 30 minutes is enough to see the foundation of Python

Basic grammar

 #Indent instead of braces #Replace semicolon with newline, or use semicolon, it doesn't matter #Output print(); #Input input(); #Notes #Single line comment """ Multiline comment 1 """ ''' Multiline Note 2 ''' #Declare variable Write letters directly and combine them with numbers and underscores instead of reserved words. # if if true: print("true") else: print("false") # while i = 0; while i <= 1: #do something print("cicle") i+=1 # for  languages = ["C", "C++", "Perl", "Python"]  for x in languages: print (x) # range The range (5) function returns an array of numbers 0~4 The range (5,9) function returns an array of numbers 5 to 8 The range (0,10,3) function returns a numeric array starting from the number 0 and increasing by 3 until the last number is less than 10 The range (- 10, - 100, - 30) function returns a numeric array starting from - 10 and increasing by - 30 until the last array is greater than - 100 #For+range traverse array with index a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ'] for i in range(len(a)) print(i,a[i]) #While traversing array with index i = 0; length = len(a); while i < a: print(i,a[i]) i+=1 #For+enumerate traverse array with index for i,value in enumerate(a): print(i,value) #List #Python list is similar to java list in nature, but not array. Its size is variable, but the elements of Python list can make different data types flexible #Create a new list list1 = [] list2 = ['bob',1,true]  #Add elements list1.append(233) List1. insert (0666) # Insert to position 0, and move the original elements backward in turn #Delete Element List2. pop() # Delete the element at the end list2.pop(0) #Modify element=direct assignment #Access the specified location element list1[2] List1 [- 1] # indicates the last element #Slice (returns a sublist) List2 [0:2] # indicates the element from index 0 to 1 List2 [- 2: - 1] # indicates the penultimate element List2 [: 3] # means from 0 to 2 List2 [1:] # means from 1 to the end #Tuple #Unlike the list, the tuple cannot be modified once it is initialized. #The list uses [] square brackets, and the tuple uses () parentheses #When defining, only one element needs to be added, to avoid ambiguity t = (1,) #Dict #Dict is similar to java map. Key value pair, Python dict is very similar to json syntax #Definition d = {'age':62, 'sex':'male'} #Access value d['age'] #Determine whether the key exists d. Get ('name ') # By default, none is returned d. Get ('name ', - 1) # Return - 1 if it does not exist 'name' in d # returns false when it does not exist #Delete key d.pop('sex') #Set #Similar to the set property of Java, it is also a collection without duplicate elements. #Definition s = set([1,1,2,2,2,3,3,'sex']) #Add Element s.add(4) s. Add (4) # Duplicate element addition will not take effect #Delete Element s. Remove ('sex ') # The parameter is the value of the set element, not the index #Function #Defining Functions def my_function(x): print(x); #Call function

Advanced Features

List Generators and Generators

List Builder

A syntax for quickly generating a list of specified conditions.

The first example: to generate a list with numbers from 0 to 10, you can use the range (0, 11) function. This is not a list generator, but just introduces the concept.

The second example: generating [1x1, 2x2, 3x3, ..., 10x10] In this way, the list formed by the product result is written in a loop:

 l = [] for x in range(1,11): l.append(x*x) #Or the following cycle i = 1 while i < 11: l.append(i*i) i+=1

Now you only need one sentence of code to use list generation:

 [x*x for x in range(1,11)]

A closer look at the above code shows that l.append(x*x) replace with x*x , written in front of the for loop, and used the list symbol as a whole [] Wrap it up.

You can also go a step further and write an if statement after the for loop to further filter the elements to be generated:

 [x * x for x in range(1, 11) if x % 2 == 0] # [4, 16, 36, 64, 100]

so to speak, List generation is a simplification of syntax, with no new function.

generator

List generation is to return a generated list.

However, if the list we need to generate is extremely large and forced into 1 million members, but we only need to print the first few elements, the space occupied by the latter multiple members will be wasted:

 L = [x * x for x in range(1000000)] print(L[0]) print(L[1])

The above writing is very wasteful and should be condemned by us. It can be written as follows:

 g = (x * x for x in range(1000000)) next(g) next(g)

This writing method returns not a list, but a generator g The generator is like a tool to remember rules At first, no element will be generated next() Generate array elements one by one.

Add 10 elements I want to generate, I can Iteration generator

 g = (x * x for x in range(10)) for x in g: print(x)

The above syntax can create a generator or yield Keyword makes a function a generator

 def odd(): print('step 1') yield 1 print('step 2') yield(3) print('step 3') yield(5) g = odd() next(g) # step 1 next(g) # step 2 next(g) # step 3 next(g) # StopIteration

You can also use the for loop to iterate over the generator:

 for x in odd(): Print (x) # Return 1, 3, 5 in turn

A function becomes a generator, using next Calling function, encountered yield Statement meeting Return the value declared by yield (constant/variable) Call again next Continue from the last returned position until the next one is encountered yield sentence.

iterator

First, we need to distinguish two concepts: Iterator and Iterable

  • Iterative object: for can be used to traverse, but it cannot be called by next (), and the next value is returned continuously.
  • Iterator: You can call next (Iterator) to continuously return the value inside the iterator
  • adopt Isinstance ([variable], Iterator) or Isinstance ([variable], Iterable) Determine whether the variable is an iterator or an iterable object
  • The list, dict, and str are not iterators in themselves. You can use iter(Iterable) Return iterator object
  • The generator itself is an iterator object.
 l = [1, 2, 3, 4, 5] lIter = iter(l) Next (lIter) # Return 1

Functional programming

Decorator

One of the design patterns is Decorator Mode In fact, it is easy to understand, that is, to extend functions. But I don't want to inherit.

Wrap the original function with the decorator function, execute the function of the decorator first, and then call the original function.

So the parameters of the decorator first The original function func_name is required, and a function needs to be defined inside the decorator wrapper , parameter is *args, **kw , represents any parameter, which is used to receive the parameters of the original function.

For example, define a log decorator that can be decorated on any function (by writing at the top of the function to be decorated @Decorator name ), execute the original function, and the call information of the function will be output:

 def log(func): def wrapper(*args, **kw): Print ("Call function% s()"% func__ name__) return func(*args, **kw) return wrapper @log     def now(str): Print ("one test function+% s"% str)

When we execute Now ("ha ha") In fact Log (now ("ha ha")) , and then call the log function internally Wrapper ("haha") , print the test time first, and then execute Now ("ha ha")


The decorator can also pass values, but there is another function inside the decorator to receive the name of the function to be decorated:

 def log(text): def decorator(func): def wrapper(*args, **kw): Print ("Call function% s() at time, test text% s"% (func. __name__, text)) return func(*args, **kw) return wrapper return decorator @Log ("Custom Text") def now(str2): Print ("one test function+% s"% str2)

Call this Now ("ha ha") , actually called Log ("user-defined text") now ("haha") , and then execute Decorator (now ("ha ha")) , the following calling process is the same as before.


The function decorated by the decorator will have a problem: printing its function name will have a problem:

such as now.__name__ , will output wrapper , we can write a sentence in the wrapper function:

 import functools def log(func): @functools.wraps(func) def wrapper(*args, **kw): Print ("Call function% s()"% func__ name__) return func(*args, **kw) return wrapper

This annotation will automatically help us wrapper.__name__ = func.__name__ Assignment.

object-oriented programming

We use the class concept of java to introduce all the object-oriented concepts of Python:

class
 class Student(object): def __init__(self, name, score, sex): self.name = name self.score = score  self.__sex = sex; def print_score(self): print('%s: %s' % (self.name, self.score)) st = Student("hewro",120,"male") print(st.name) st.print_sore()

From the above code, we can see that:

  • The member variable is in the __init__ Rather than declaring variables directly
  • The constructor name is __init__ , Python does not support function overloading. Naturally, there can only be one constructor. And the first parameter must be self , you do not need to call this parameter manually when generating an instance.
  • To use its own variable inside a class, you need to add it to the first parameter of the function self , very troublesome
  • The writing method of inheriting parent class is not extend , but (Parent class)
  • There is no keyword in the definition of python's private variable, just two underscores in front of the variable name __ , such as __sex , you cannot print directly std.__sex
About polymorphism

We know that polymorphism is a good feature of inheritance. Java and Python are available. However, Python itself does not need to declare the type of variables, so polymorphic implementation does not necessarily need to be a subclass that defines the parent class, but as long as the object also has a specified method (that is, a duck type).

For example, we have a parent class of Animal, as well as Dog and Cat subclasses that inherit Animal

 class Animal(object): def run(self): print('Animal is running...') class Dog(Animal): def run(self): print('Dog is running...') class Cat(Animal): def run(self): print('Cat is running...') class Tortoise(Animal): def run(self): print('Tortoise is running slowly...') #The parameters of this function are not actually declared def run_twice(animal): animal.run() animal.run()

So execute run_twince() Parameters can be dog Instance, or Tortoise An instance of, although Tortoise Not inherited from Animal

Last modification: March 28, 2019
Do you like my article?
Don't forget to praise or appreciate, let me know that you accompany me on the way of creation.