Python _ basic syntax _ 01, python basic syntax _ 01

Source: Internet
Author: User

Python _ basic syntax _ 01, python basic syntax _ 01

There are still a few months before graduation. I wanted to go to the company for an internship early, but I don't want to release the gb School. Well, in this case, learn the language.

Reference and http://www.cnblogs.com/vamei, I followed this blog tutorial, specific you can view the blog of this blogger.

Remember to stick the code and comments of the small examples of exercises to prevent you from forgetting them.

# Coding: utf-8from logging import exceptionfrom xmlrpclib import DateTime # define class Info (): age = 2 class Person (): # parameters in parentheses represent the inherited object, the constructor parameter name = 'hefei' age = 25 def sayHello (self, content): # The member function must include the print content def _ init _ (self, info): # It is equivalent to a constructor. It is used to initialize some attributes of self when an object is created. age = Info. age # class inheritance. When a class is created, the inherited parent class American (Person): shengao = 1.88i = Info () a = Person (I) # map assignment is written in brackets, in python, it is nothing more than a key-value pair. It is a mapm = {'Nam E': 'heifei', 'age': 25} m. setdefault ('shenggao') m ['shenggao'] = 1.88for I in m. values (): print iworkflow file fw.open('test.txt ', 'R') content = f. readline () f. close () print content # several useful methods for loop statements S = 'abcdefghjk 'for I in range (0, len (S), 2 ): # The last parameter indicates the number of hops print S [I] S = 'abcdefghijk 'for (index, char) in enumerate (S): # When performing iteration on list or tuple, the enumeration method can obtain the index of the list, index print char # zip, and package. You can pack the list with the same length. For example, the result after packaging is as follows: [(1 ,' A'), (2, 'B'), (3, 'C')] ta = [1, 2, 3] tb = ['A', 'B ', 'C'] zipped = zip (ta, tb) print type (zipped), zipped # unzipta1, tb1 = zip (* zipped) # * indicates the meaning of the solution package, the solution package is based on "," split print ta1, tb1, type (ta1) # package again, and change back, but the type has changed, haha, the design is really good result = zip (ta1, tb1) print comment ') # The file object here is a loop object for line in f: print line # generator: Custom iteration object. During each iteration, yield is returned, in the next iteration, def gen (): a = is iterated from the previous yield place. 1 yield a = a + 1 yield afor I in gen (): print I # Table derivation. Like a custom iterator, there is a short expression, table derivation is used to quickly generate the required list. It does not feel very useful. L = [] for x in range (10): L. append (x ** 2) print Lxl = [1, 3, 5] yl = [9, 12, 13] L = [x ** 2 for (x, y) in zip (xl, yl) if y> 10] print L # lambda function, in the object-oriented world, function is also an object func = lambda x, y: x + yprint func) # lambda expressions are equivalent to conventional method definitions def func (x, y): return x + yprint func (2, 3) # several special methods # map function: returns a list, the result is the list processed by the method in the original list, and the returned result is [3, 5] print map (lambda x: x + 1, [2, 4]) # reduce method, iterative thinking, use the result after processing the previous method as the parameter for processing the result. The returned result is 6 print reduce (lambda x, y: x + y, [, 3]). # Exception Handling re = iter (range (5); # Use the iter method to define an iteration object try: for item in range (10): # print re for 10 iterations. next () wait t StopIteration: print 'here is the end', itemfinally: print 'this is finaly' # throw an exception object by yourself. raise keyword raise StopIteration # dynamic type, references in the independent example, a + 2. Although B points to a, B's value remains unchanged # objects in python are classified as mutable and immutable objects, such as tuple) and the string are non-mutable objects, and the others are mutable objects, which are the same as java a = 5b = aa = a + 2 print 'a = ', a,' B = ', B # api introduction in the standard library print DateTime () # python deep learning # context MANAGER: defines the scope of the file object. In the with statement, although f is not manually disabled, however, as long as the with statement block is exceeded, the object is automatically closed. In fact, the built-in functions of the class are executed separately, __enter _ and _ exit _ with open('test.txt ', 'w ') as f: print f. closedprint f. closed # You can customize the context manager class Teller (object): def _ enter _ (self): print 'I m come' def _ exit _ (self, fexc_type, exc_value, traceback): # Here Nima does not give a prompt. Here, the _ exit _ method requires four parameters: print 'I m out' with Teller () as teller: # There must be a statement in the with statement block. Otherwise, the explanation does not pass the print 'running .. '# function object, which is equivalent to the internal java object def out_fun (): def in_fun (): return 2 print in_fun () out_fun () # closure. The program running result below is 25, my -- line = line_conf () returns a function object. Input 5 to perform 2*5 + B operations, the value of B defined by the external function # Here, B is also called the environment variable of the internal function object. A function object is called a closure together with its environment variable, the value of environment variables is placed in the _ closure _ attribute of the function object. This attribute is a tuples # the advantage of closure is that it reduces the setting of function parameters, def line_conf (): B = 15 def line (x ): return 2 * x + B return line # return a function objectb = 5my_line = line_conf () print (my_line (5) print my_line. _ closure _ [0]. cell_contents # The decorator is equivalent to a dynamic proxy in java. It modifies the original method to enhance it # defines a decorator. The decorator is a modifier function, therefore, the received parameter is also a function object. In addition, the modifier can also modify the class. The Code is as follows: def decorator (F): def new_F (): print "this is the enhancement content" return F () # F () must be used here. F () is not used; otherwise, the result cannot be obtained. The closure feature is embodied here, the internal function calls the external environment variable return new_F # returns the processed function object @ decoratordef F (): print "original content" F () # The decorator Can also modify the class def decorator1 (aClass): class newClass: def _ init _ (self, age): self. total_display = 0 self. wrapped = aClass (age) def display (self): self. total_display + = 1 print ("total display", self. total_display) self. wrapped. display () return newClass @ decorator1class Bird: def _ init _ (self, age): self. age = age def display (self): print ("My age is", self. age) eagleLord = Bird (5) for I in range (3): eagleLord. display () # Tips # When modules with test statements are introduced by other modules, in other modules, if _ name __= = '_ main _': Test code def localMethod (): print "hello" if _ name __= = '_ main _': print 'test Content'

..

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.