Python re-learn notes

Source: Internet
Author: User

Python a variety of half-bucket water qaq, some features often mixed with other languages, the official entry document reread ...

It's best to indent in 4 spaces
A null value is a special value in Python, denoted by none
Variables are used in programs to point to these data objects, assigning values to variables is to associate the data with the variables.

Coding issues:
Print u ' in '. Encode (' Utf-8 ')

Another ordered list is called a tuple: a tuple. The tuple and list are very similar, but the tuple cannot be modified once initialized, such as the name of the classmate: classmates = (' Michael ', ' Bob ', ' Tracy ')

Can be represented by a list: classmates = [' Michael ', ' Bob ', ' Tracy ']

Write a dict in Python as follows:
>>> d = {' Michael ': Up, ' Bob ': +, ' Tracy ': 85}

Set is similar to Dict and is a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set.
To create a set, you need to provide a list as an input collection: s = set ([1, 2, 3])

If you are careful not to write a colon less:

If Age >= 6:
print ' teenager '

For x in range (100):
sum = sum + x

You must first cast the string to the integral type we want with int ():
birth = Int (raw_input (' Birth: '))

In Python, you define a function to use the DEF statement, and the return value of the function is returned with a return statement.
Let's take the example of a custom my_abs function that asks for an absolute value:
def my_abs (x):
If x >= 0:
return x
Else
Return-x

Def NOP ():
Pass
The pass can actually be used as a placeholder, such as the code that is not yet ready to write the function.

Can a function return multiple values? The answer is yes.
Return NX, NY

Be aware of the syntax for defining mutable parameters and keyword parameters:

The *args is a mutable parameter, and args receives a tuple
**KW is the keyword parameter, and kw receives a dict

Corresponding to the above problem, take the first 3 elements, a line of code to complete the slice:
>>> L[0:3]

Create a generator:l = [x * x for x in range (10)]

corresponding to the programming language, is the lower level of the language, the more close to the computer, low degree of abstraction, implementation of high efficiency, such as C language, the more advanced language, the more close to the computation, high degree of abstraction, inefficient execution, such as Lisp language. One of the features of functional programming is that it allows the function itself to be passed as a parameter to another function, and also allows a function to be returned! Conclusion: The function itself can also be assigned to the variable, that is: The variable can point to the function.

Python's built-in sorted () function allows you to sort the list: sorted ([36, 5, 12, 9, 21])

Normal functions and variable names are public and can be directly referenced, for example: ABC,X123,PI, etc.;

A variable like __xxx__ is a special variable that can be referenced directly, but has a special purpose, such as the __author__,__name__ above is a special variable, and the document annotation defined by the Hello module can also be accessed with a special variable __doc__. Our own variables are generally not used in this variable name;
Functions or variables such as _xxx and __xxx are non-public (private) and should not be referenced directly, such as _ABC,__ABC, etc.

Python has two package management tools that encapsulate Setuptools: Easy_install and Pip. Currently, it is recommended to use PIP.
eg.: Pip install PIL

Python provides the __future__ module to import the next new version of the feature into the current version, so we can test some of the features of the new version in the current version.

Object-oriented:

Class Student (object):

def __init__ (self, Name, score):
Self.name = Name
Self.score = Score

def print_score (self):
Print '%s:%s '% (Self.name, Self.score)

Class names are followed by classes, that is, student, where the class name is usually the first word in uppercase, followed by (object), indicating which class the class inherits from.

__init__ and __del__ perform initialization and deletion operations separately

At any time, if no suitable class can inherit, it inherits from the object class.

With multiple inheritance, a subclass can get all the functionality of multiple parent classes at the same time.


Class TestClass (object):
VAL1 = 100

def __init__ (self):
Self.val2 = 200

def FCN (Self,val = 400):
VAL3 = 300
Self.val4 = Val
SELF.VAL5 = 500

Here, Val1 is a class variable that can be called directly by the class name, or it can have objects to invoke;
Val2 is a member variable that can be called by the object of the class, and here you can see that the member variable must be given in the form of self, because self means to represent an instance object;
Val3 is not a member variable, it is just a local variable inside the function FCN;
Val4 and VAL5 are also not member variables, although they are given as self. But are not initialized in the constructor.

So high-level languages are usually built into a set of try...except...finally ... Error-handling mechanism, Python is no exception.

When we think that some code may be wrong, you can use try to run the code, if the execution error, the subsequent code will not continue to execute, but directly jump to the error-handling code, that is, except statement block, after the execution of except, if there is a finally statement block, Executes the finally statement block, which completes the execution. Finally if there is, it is bound to be executed (there can be no finally statement).

If you want to throw an error, you can first define an incorrect class, choose a good inheritance relationship, and then throw an instance of the error with the raise statement, as needed.

Python's OS module encapsulates common system calls, including fork, which makes it easy to create sub-processes in a Python program

Under Unix/linux, the multiprocessing module encapsulates the fork () call, so that we do not need to focus on the details of the fork (). Because Windows does not have a fork call, multiprocessing needs to "emulate" the effect of a fork, and all Python objects of the parent process must be serialized to the child process via pickle, all, If multiprocessing fails in Windows downgrade, first consider if Pickle failed.

Multitasking can be done by multiple processes or by multithreading within a process.

Python's standard library provides two modules: thread and Threading,thread are low-level modules, and threading is an advanced module that encapsulates thread. In most cases, we only need to use the Advanced module threading.

With the knowledge of readiness, we can use regular expressions in Python. Python provides the RE module, which contains the functionality of all regular expressions.

Python's built-in module Itertools provides useful functions for manipulating iterative objects.

Fortunately, Python provides htmlparser to parse HTML very easily, with just a few lines of code:

Pil:python Imaging Library, is already the Python platform in fact the image processing standard libraries. The PIL feature is very powerful, but the API is very easy to use.

So, we're going to create a TCP connection-based socket that can do this:

# Import the Socket library:
Import socket
# Create a socket:
s = socket.socket (socket.af_inet, socket. SOCK_STREAM)
# to establish a connection:
S.connect (' www.sina.com.cn ', 80)


[Import Fibo]
Doing so does not directly import the functions in Fibo into the current semantic table; it simply introduces the module name Fibo.


A variant of the import statement is imported directly from the imported module into the semantic table named in this module. For example:
>>> from Fibo import fib, fib2
>>> FIB (500)


There is even a way to import all the definitions in the module:
>>> from Fibo Import *

In the From AAA import BBB:
AAA is a module
BBB is a method or a class search
The BBB is under AAA.

Use if __name__ = = ' __main__ ' to determine if the. py file is running directly


1.os and OS Related

2.time is time-related

3.pcap Grab Bag

4.DPKT Unpacking and Packaging

5.pymssql operation of MSSQL database

6.cProfile self-debug script performance, can accurately and quickly calculate run time

7.urllib2 one of the first contact libraries, related to HTTP

8.httplib related to HTTP

9.smtplib of Lib for SMTP

Lib of 10.poplib POP3

11.tarfile Solution Tar Package

12.socket the most original TCP library

13.paramiko SSH SFTP

14.psyco enhanced performance, very efficient for functions and classes, especially with multiple loops

15.pywin32 using the Windows API

16.selenium Interface Automation

17.sqlite3 Sqlite3 Database Operations

Encoding and decoding of 18.EMAIL messages

19.stackless Micro-threading, according to the relevant person test, can achieve 10 times times the normal thread performance

20.WX Wxpython, write interface with

21.py2exe the PY program into EXE executable

22.shutil is useful, copy, delete

23.thread Normal Thread

Python re-learn notes

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.