Python study notes,

Source: Internet
Author: User

Python study notes,

I recently read the Python tutorial, so I will record some of it. If I read it myself later, the review will be faster.

 

Print ("I am ***", "What about you? ", True) # Replace the comma with a space and splice it with name = input (" Your name: ") # enter the string value: integer, floating point, String, null, Boolean: and or notstr: '1 '. replace ('1', '2') isinstance (x, (int, float) Check whether x belongs to int or floatprint (ord ('A ')) # encoding print (chr (97 ))

 

  List and tuple

# The elements in the list can be different names = ['bob', 'Mary ', 'jack'] print (len (names) print (names [0]) print (names [-1]) names. append ('dav') # append names. insert (1, 'kery ') # insert. The first parameter is the position names. pop (3) # Delete the specified position names [1] = 'arry' # Replace names. sort () # sort # tuple tuples, similar to list (parentheses are replaced with parentheses, which can be used in other methods), but cannot be changed after initialization # because there are Parentheses in the mathematical formula, therefore, an element must contain a comma, t = (1,) # The unchanged tuple indicates that the point is unchanged. For example, if a list exists in the tuples, the point of the list remains unchanged, however, the value in the list can be changed to t = (, []) t [2] [0] = 5

 Conditional judgment and loop

# Condition judgment cl = 5if cl <= 6: print (' ') elif cl <= 9: print ('') elif cl <= 12: print ('high school') else: print ('University or unreaded') # loop names = ['bob', 'Mary ', 'jack'] for name in names: print (name) n = 0 while n <len (names): print (names [n]) n = n + 1

 Dict and set

# Dict dictionary, in the form of key-value pairs, the search speed is fast, the key is not changeable, so the key cannot be listd = {'1': 1, '2 ': 2} print (d ['1']) d ['1'] = 11 # change the value if '1' in d: # avoid the error print (d ['1']) print (d. get ('1') # If the key does not exist, return Noned. pop ('1') # Delete this value, and the value will also be deleted for k, v in d. items: print (k, v) #===================================================== ================================================ # there is no relationship between the order in which dict stores data and the order in which keys are placed. # Compared with list, dict has the following features. # The opposite is list: # therefore, dict is a way to exchange space for time. #===================================================== ================================================ # Set key set, repeat is not allowed. s1 = set ([,]) # repeat elements automatically filter s1.add (20) s1.remove (20) s2 = set ([, 3]) # set can be regarded as a set of unordered and non-repeating elements in the mathematical sense. Therefore, the two sets can perform operations such as intersection and union in the mathematical sense: print (s1 & s2) print (s1 | s2)

  Built-in functions, functions, and parameters

# Python built-in function abs (100) max (123, 123) min (,) int ('123') float ('123. 43 ') str (1.24) bool (1) # function def nop (): pass #=================================================== ========================================================== # parameter # * args is a variable parameter, args receives a tuple; # ** kw is a keyword parameter, and kw receives a dict. #===================================================== ========================================================

 Slice

# Slice list, tuple, and str available names = ['bob', 'Mary ', 'jack'] print (names [0: 2]) print (names [: 2]) print (names [-2:]) # print (names [: 3: 2]) # Get one for every two

  Iteration

# Iteration from collections import Iterableprint (isinstance ('abc', Iterable) # The built-in enumerate function can convert a list into an index-element pair for I, value in enumerate (['1', '2', '3', '4']): print (I, value)

  List Generator

# List generative print (list (range (1, 33) l = [x * x for x in range (1, 4)] print (l) l = [x * x for x in range (1, 11) if x % 2 = 0] print (l) l = [m + n for m in 'abc' for n in 'xyz'] print (l) # generator stores algorithm g = (x * x for x in range () # Replace brackets with parentheses and generate print (next (g )) # print the next value, and an error will be reported at the end, so use the for loop # replace print with yield, and the function becomes generator

  Map, reduce, filter

# Map (fun, Iterable) sequentially applies the passed functions to each element of the sequence, and returns the result as a new Iterator def f (x ): return x * xprint (list (map (f, [1, 2, 3, 4]) # reduce (fun, Iterable) perform the cumulative calculation of the result continuation and the next element of the sequence from functools import performancedef add (x, y): return x + yprint (reduce (add, [1, 2, 4]) # filter (fun, Iterable) applies the input function to each element in sequence, and determines whether to retain or discard the element based on whether the returned value is True or False. Def is_odd (x): return x % 2 = 1 print (list (filter (is_odd, [1, 2, 3, 4, 5])

  Small sorting example

#================= Sorting Problem ==================================== ========================================================== = # def by_name (t): # return t [0] # L = [('bob', 75), ('Adam ', 92), ('bart', 66), ('lisa ', 88)] # print (sorted (L, key = by_name) # print (sorted (['bob', 'about', 'zoo', 'credentials'], key = str. lower, reverse = True )) # case-insensitive ##======================================================== ========================================================== ===

 Anonymous functions and closures

# Anonymous function print (list (map (lambda x: x * x, [1, 2, 3]) # closure def count (): fs = [] def f (x): return lambda: x * x # using the anonymous function for I in range (1, 4): fs. append (f (I) return fsf1, f2, f3 = count () print (f1 (), f2 (), f3 ())

  Small decorator example

# Run the decorator to check import functoolsdef logger (text): def decorator (func): @ functools. wraps (func) def wrapper (* args, ** kw): print ('% s ():' % (text, func. _ name _) return func (* args, ** kw) return wrapper return decorator @ logger ('debug') def today (): print ('2014-3-25 ') today ()

  Partial function

# Partial functions can reduce the difficulty of function calling. import functoolsmax2 = functools. partial (max, 10) print (max2 (1, 2, 3, 4 )) # automatically place 10 in the Compare value #============================================ ========================================================== ========##. the py file is called a module. ========================================================== ====

 Class and instance

# Class and instance # variable names are similar to _ xxx _. They start with a double underline and end with a double underline. Special variables can be directly accessed, it is not a private variable. class Student (object): def _ init _ (self, name, score): # _ init _ the first parameter of the method is always self, the self. _ name = name # indicates private self. _ score = score # _ name. Such instance variables can be accessed externally, meaning, "Although I can be accessed, Please treat me as a private variable, ". Def print_score (self): print (self. _ name, self. _ score) def get_name (self): return self. _ name def set_name (self, name): self. _ name = name def set_score (self, score): self. _ score = score def get_score (self): return self. _ scores = Student ('bart', 14) #__ name cannot be accessed because it is changed to _ St05udent _ nameprint (s. _ Student _ name) s. _ name = '000000' # The internal _ name variable has been automatically changed to _ Student _ name by the Python interpreter, the external code adds a Variable _ name to bart. Print (s. get_name () # s. print_score () # inheritance and polymorphism class ChuStudent (Student): # Junior High School Students inherit def set_score (self, score): if score <= 100: self. _ score = score else: print ('incorrect score ') chu = ChuStudent ('123', 40) chu. set_score (143) chu. print_score () # obtain the Object type print (type (123) import types # determine whether an object is a function print (type (lambda x: x * x) = types. lambdaType) print (isinstance ('A', str) print (dir ('000000') # obtain all attributes and method print (hasattr (chu, 'name ')) # Whether the name attribute setattr (chu, 'age', 10) # Set the attribute print (getattr (chu, 'age') # obtain the attribute print (chu. age) # print (getattr (chu, 'z', 404) that will throw AttributeError if the property does not exist. # assign the default value to the end. # bind the def set_age (self, age ): self. age = agefrom types import MethodTypes. set_age = MethodType (set_age, s) s. set_age (120) print (s. age) # If you bind methods to all instances, ChuStudent. set_age = set_age # Restrict instance attributes class XiaoStudnet (Student): _ slots __= ('name', 'score ', 'age ') # Use tuple to define the attribute names that can be bound

@ Property usage

#===================================================== ============================================================ ## @ Property # class Student (object): # birth is a read/write attribute, while age is a read-only attribute. # @ property # def birth (self): # return self. _ birth ##@ birth. setter # def birth (self, value): # self. _ birth = value ##@ property # def age (self): # return 2015-self. _ birth ### multi-inheritance # class Object1 (Object2, Object3 ....): # pass #=================================================== ==========================================================

  Adding a print for the instance is equivalent to overwriting toString in java

#===================================================== ============================================================ ## Add a print display for the instance # class Student (object): # def _ init _ (self, name): # self. name = name # def _ str _ (self): # return 'student object (name = % s) '% self. name # _ repr _ = _ str __# # print (Student ("123 ")) #===================================================== ==============================================

 You can use the for loop for objects.

#===================================================== ============================================================ ## If a class is used... in loop. Like list or tuple, A _ iter _ () method must be implemented. This method returns an iteration object # class Fib (object ): # def _ init _ (self): # self. a, self. B = 0, 1 # initialize two counters a, B # def _ iter _ (self): # return self # The instance itself is an iteration object, therefore, the returned result is self # def _ getitem _ (self, n): # direct f [] display # if isinstance (n, int): # n is the index #, B = 1, 1 # for x in range (n): # a, B = B, a + B # return a # if isinstance (n, slice ): # n is a slice # start = n. start # stop = n. stop # if start is None: # start = 0 # a, B = 1, 1 # L = [] # for x in range (stop): # if x> = start: # L. append (a) # a, B = B, a + B # return L # def _ getattr _ (self, attr): # prevent nonexistent attributes, error # if attr = 'score ': # return 99 # def _ call _ (self): # You can call the instance s () directly () # print ('My name is % s. '% self. name) # def _ next _ (self): # self. a, self. B = self. b, self. a + self. B # Calculate the next value # if self. a> 100000: # condition for exit loop # raise StopIteration () # return self. a # return the next value #================================================ ========================================================== ===

 Enumeration

#===================================================== ============================================================ ## If a class is used... in loop. Like list or tuple, A _ iter _ () method must be implemented. This method returns an iteration object # class Fib (object ): # def _ init _ (self): # self. a, self. B = 0, 1 # initialize two counters a, B # def _ iter _ (self): # return self # The instance itself is an iteration object, therefore, the returned result is self # def _ getitem _ (self, n): # direct f [] display # if isinstance (n, int): # n is the index #, B = 1, 1 # for x in range (n): # a, B = B, a + B # return a # if isinstance (n, slice ): # n is a slice # start = n. start # stop = n. stop # if start is None: # start = 0 # a, B = 1, 1 # L = [] # for x in range (stop): # if x> = start: # L. append (a) # a, B = B, a + B # return L # def _ getattr _ (self, attr): # prevent nonexistent attributes, error # if attr = 'score ': # return 99 # def _ call _ (self): # You can call the instance s () directly () # print ('My name is % s. '% self. name) # def _ next _ (self): # self. a, self. B = self. b, self. a + self. B # Calculate the next value # if self. a> 100000: # condition for exit loop # raise StopIteration () # return self. a # return the next value #================================================ ========================================================== ===

 Error Handling

#===================================================== ============================================================ ## Error Handling # try: # r = 10/0 # failed t Exception as e: # print (e) # finally: # print ('Finally... ') # print ('end ') #===================================================== ==============================================

  Read/write files

#===================================================== ============================================================ ## Read/write files # try: # f=open('test.txt ', 'R') # print (f. read () # finally: # if f: # f. close () # with open('test.txt ', 'R') as f: # print (f. read () # prevent files from being too large and read in one row # for line in f. readline (): # print (line. strip () # with open('test.txt ', 'w') as f: # f. write ('hello, world! ') #===================================================== ==============================================

  StringIO and BytesIO

# Reading and Writing strfrom io import StringIOf = StringIO () print (f. write ('hello') s = f. getvalue () from io import StringIOf = StringIO ('Hello! ') While True: s = f. readline () if s = '': break print (s. strip () from io import BytesIOf = BytesIO () print (f. write ("Chinese ". encode ('utf-8') print (f. getvalue () from io import BytesIOf = BytesIO (B '\ xe4 \ xb8 \ xad \ xe6 \ x96 \ x87') print (f. read ())

  Operation directories and files

# Import osprint (OS. name) # posix is a linux system, nt is a windows system print (OS. environ) # environment variable print (OS. environ. get ('path') # print (OS. path. abspath ('. ') # view the absolute path of the current directory print (OS. path. join ('C: \ Users \ Administrator \ Desktop \ PythonLeaning ', 'testdir') # combine the two directories to print (OS. mkdir ('C: \ Users \ Administrator \ Desktop \ PythonLeaning \ testdir') # create a directory print (OS. rmdir ('C: \ Users \ Administrator \ Desktop \ PythonLeaning \ testdir ') ) Print (OS. path. split ('C: \ Users \ Administrator \ Desktop \ PythonLeaning ') # split the path and the last one to print (OS. path. splitext ('C: \ Users \ Administrator \ Desktop \ PythonLeaning \ test.txt ')) # Getting file extensions # These merge and split paths do not require that directories and files actually exist. They only operate on strings. Print( OS .rename('test.txt ', 'test. py ') # rename print (OS. remove ('test. py ') # delete the file print ([x for x in OS. listdir ('. ') if OS. path. isdir (x)]) # print ([x for x in OS. listdir ('. ') if OS. path. isfile (x) and OS. path. splitext (x) [1] = '. py ']) # list all. py file

 Serialization and JSON

# Serialization: the process of changing variables from memory to storage or transmission is called serialization import handler ', 'rb') d = pickle. load (f) f. close () print (d) # JSON import jsond = dict (name = 'bob', age = 20, score = 99) print (json. dumps (d) # Return the standard json format json_str = '{"name": "Bob", "age": 20, "score ": 99} 'print (json. loads (json_str) # instance serialization class Student (object): def _ init _ (self, name, age, SC Ore): self. name = name self. age = age self. score = score def student2dit (std): return {'name': std. name, 'age': std. age, 'score ': std. score} s = Student ('bob', 20, 99) print (json. dumps (s, default = student2dit) print (json. dumps (s, default = lambda obj: obj. _ dict _) # A class instance usually has a _ dict _ attribute, which is a dict used to store instance variables. # Deserialization def dict2student (d): return Student (d ['name'], d ['age'], d ['score ']) print (json. loads (json_str, object_hook = dict2student ))

  Thread

# The OS module of the thread python encapsulates common system calls. import osfrom multiprocessing import Process # the code to be executed by the sub-thread def run_proc (name): print (name, OS. getpid () if _ name __= = '_ main _': print (OS. getpid () p = Process (run_proc ('test') print ('start') p. start () p. join () # Wait until the sub-process ends and continue to run. It is usually used for inter-process synchronization. Print ('termination') # If you want to start a large number of sub-processes, you can use the process pool to create sub-processes in batches from multiprocessing import Poolimport time, randomdef long_time_task (name ): print (name, OS. getpid () start = time. time () time. sleep (random. random () * 3) end = time. time () print (name, (end-start) if _ name __= = '_ main _': print ('Waiting for completion ') print (OS. getpid () p = Pool (4) for I in range (5): p. apply_async (long_time_task (I) p. close () p. join () print ('complete') from multiprocessing im Port Process, Queueimport OS, time, random # code for writing data Process execution: def write (q): print ('process to write: % s' % OS. getpid () for value in ['A', 'B', 'C']: print ('put % s to queue... '% value) q. put (value) time. sleep (random. random () # code executed by the read data Process: def read (q): print ('process to read: % s' % OS. getpid () while True: value = q. get (True) print ('get % s from queue. '% value) if _ name __= =' _ main _ ': # create a Queue for the parent process and pass it to each sub-process Process: q = Queue () pw = Process (target = write (q,) pr = Process (target = read (q,) # promoter Process pw, write: pw. start () # promoter process pr, read: pr. start () # Wait for the completion of pw: pw. join () # in the pr process is an endless loop and cannot wait until it ends. It can only be forcibly terminated: pr. terminate () # The global variable local_school is a ThreadLocal object. Each Thread can read and write the student attribute but does not affect each other. You can regard local_school as a global variable, but each attribute, such as local_school.student, is a local variable of the thread. It can be read and written without interfering with each other and does not need to manage the lock. ThreadLocal will handle it internally. # It can be understood that the global variable local_school is a dict. It can not only use local_school.student, but also bind other variables, such as local_school.teacher. # ThreadLocal is most commonly used to bind a database connection, HTTP request, user identity information, and so on to each thread, in this way, all the called processing functions of a thread can easily access these resources. Import threading # create a global ThreadLocal object: local_school = threading. local () def process_student (): # Get the student associated with the current thread: std = local_school.student print ('hello, % s (in % s) '% (std, threading. current_thread (). name) def process_thread (name): # student bound to ThreadLocal: local_school.student = name process_student () t1 = threading. thread (target = process_thread, args = ('Alice ',), name = 'thread-a') t2 = threading. thread (target = process_thread, args = ('bob',), name = 'thread-B ') t1.start () t2.start () t1.join () t2.join ()

  

 

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.