Python Full learning Notes

Source: Internet
Author: User

Dir (__builtins__)

Help (Input)

' Let\ ' go ' #转义字符 \

R ' C:\now ' #字符串前加r auto-escape

Str= ""

Shdiufhi

Sdfjskldfjk

Dfdfsdf

"#多行打印

Isinstance (i, str) #判断是否符合str类型

#地板除法

2 * * 4 #16 Power operation

-3 * * 2 #-9 priority problem is lower than left priority higher right

small = x if x<y else y #三元操作符

Assert 3>4 #断言 wrong throw exception assertionexception

Print (I, end = ") #

List.append ()

List.extend () #参数中传入的数组进行组合

List.insert (1,value) #根据位置插入到列表中

List.remove () #移除目标

Del List[1] #从内存中删除列表元素

List.pop () #随机pop或指定索引

list[:] #获得列表的拷贝

List can be added

in# can be used to determine whether the list contains

' {0} love {1} '. Format (' I ', ' u ')

' {A} love {b} '. Format (a= ' i ', b= ' u ')

' {0:.1f}{1} '. Format (12.32323, ' MFC ')

Sequence list Turple string

List (' Mengfanchen ')

Turple (' Mengfanchen ')

Sorted () #排序方法

Enumerate () #转为元组

a=[1,2,3,4,5,6,7]

b=[3,5,7,4,8]

List (A, B) =[(1,3), (2,5), (3,7), (bis), (5,8)]# Well, it should be useful.

Function:

Ming rule First Letter Capital Mengfanchen ()

Function Documentation:

def mengfanchen (' name ', ' age '):

' This is an example '

Print (' This is mengfanchen! ')

MENGFANCHEN.__DOC__ will return to the above ' this is an example '

Keyword parameters

Mengfanchen (name = ' Mengfanchen ', age= ' 17 ')

Default parameters

Collect parameters

def test (*params):

Print (' hahaha ', Len (params)

def test (**kwargs):

For key in Kwargs:

print "Another keyword ARG:%s:%s"% (key, Kwargs[key])

Inline functions and closures:

Count = 5

Def myfun ():

Global Count

count=10

Print (count) #全局变量被修改global关键字

def funx (x):

def funy (y):

Return X*y

Return Funy

Funx (5) (8)->40 #FunY即为一个闭包

i = Funx (5)

Type (i)-function #即为FunY

Def Fun1 ():

x = 5

Def Fun2 ():

nonlocal x

X *= x

return x

Return Fun2 () #nonlocal关键字可使Fun2 () Use external variable x or use x[] because it is not treated as a local variable

Lambda (anonymous function):

g= Lamda x:2*x+1

Print (g (5)) #lamda省下定义函数的过程

Filter: Filtering

List (filter (None, [1,0,falsr,true]))

->[1,true] #默认过滤出True类型

Temp =range (10)

def odd (x):

Return x%2

Print (List (filter (odd, temp)))

->[1,3,5,7,9] #仔细想想是怎么求奇数的

Use lambda to implement the above example

List (filter (lambda x:x%2, range)) #很强

Map: Map

List (map (lambda x:x*2, Range (10)))

[0,2,4,6,8,10,12,14,16,18] #map也有点有用

Recursion:

Import Sys

Sys.setrecursionlimit (100000) #设置递归深度

Dictionaries and collections:

Dict1 = Dict.fromkeys ([1,2,3,4,5], ' mengfanchen ')

{1: ' Mengfanchen ', 2: ' Mengfanchen ', 3: ' Mengfanchen ', 4: ' Mengfanchen ', 5: ' Mengfanchen '}

6 in Dict1->false

Set: Unique & unordered

num = [1,2,3,4,5,5,6]

num = list (set (num)), [1,2,3,4,5,6]

Frozenset: Immutable Collection

Standard read-in file mode:
For Each_line in F:

Print (Each_line) #官方文档推荐形式

A module is a file that contains all the functions and variables. py files can be introduced into the available.

OS Module

Name of function

How to use

GETCWD ()

Return to current working directory

ChDir (PATH)

Change the working directory

Listdir (path= '. ')

Enumerates the file names in the specified directory ('. ') Represents the current directory, ' ... ' Indicates the previous level of the directory)

mkdir (PATH)

Create a single-level directory, such that a thrown exception already exists in the directory

Makedirs (PATH)

Recursive creation of multi-level catalogs, such as the directory already exists thrown exception, note: ' e:\\a\\b ' and ' e:\\a\\c ' do not conflict

Remove (PATH)

deleting files

RmDir (PATH)

Delete a single-level directory, which throws an exception if the directory is not empty

Removedirs (PATH)

Recursively delete directories, from subdirectories to parent directories, and try to delete them, and throw exceptions when the directory is not empty

Rename (old, new)

Rename the file old to new

System (Command)

Shell command to run the system

Walk (top)

Iterate through all subdirectories below the top path, returning a ternary group: (path, [include directory], [include file])

The following are some of the definitions that are commonly used in support path operations, supporting all platforms

Os.curdir

Refers to the current directory ('. ') )

Os.pardir

refers to the upper level directory ('.. ') )

Os.sep

Output operating system-specific path delimiter (win under ' \ \ ', Linux under '/')

Os.linesep

The line terminator used by the current platform (win under ' \ r \ n ', Linux ' \ n ')

Os.name

Refers to the currently used operating system (including: ' POSIX ', ' NT ', ' Mac ', ' os2 ', ' CE ', ' java ')

How to use the function of path commonly used in Os.path module

Name of function

How to use

basename (PATH)

Remove directory path, return file name separately

DirName (PATH)

Remove the file name and return the directory path separately

Join (path1[, path2[, ...])

Combine the path1, path2 parts into a path name

Split (PATH)

Splits the file name with the path, returning the tuple (F_path, f_name). If the directory is fully used, it also separates the last directory as a file name and does not determine whether the file or directory exists

Splitext (PATH)

Detach file name and extension, return (f_name, f_extension) tuple

GetSize (file)

Returns the size of the specified file, in bytes

Getatime (file)

Returns the last access time of the specified file (floating-point number of seconds, which can be converted using the gmtime () or localtime () function of the time module)

Getctime (file)

Returns the creation time of the specified file (floating-point number of seconds, which can be converted using the gmtime () or localtime () function of a time module)

Getmtime (file)

Returns the latest modification time of the specified file (floating-point number of seconds, gmtime () or localtime () function conversion of the time module)

The following is a function that returns TRUE or False

Exists (PATH)

Determines whether the specified path (directory or file) exists

Isabs (PATH)

Determines whether the specified path is an absolute path

Isdir (PATH)

Determine if the specified path exists and is a directory

Isfile (PATH)

Determines whether the specified path exists and is a file

Islink (PATH)

Determines whether the specified path exists and is a symbolic link

Ismount (PATH)

Determine if the specified path exists and is a mount point

Samefile (path1, paht2)

Determine if the two paths of path1 and path2 point to the same file

Pickle Module (object, binary conversion to each other)

Temp = [1,2,3,4,5]

Pickle_file = open (' Temp.pkl ', ' WB ')

Pickle.dump (temp, pickle_file)

Pickle.close

Pickle_file = open (' temp.pkl ', ' RB ') #read binary

Temp = Pickle.load (pickle_file)

Exception handling:

Several statements, try Catch finally raise

Else (try to execute the ELSE statement after you can add else, or do not error)

With (can look in detail, feel very high-end)

Assertionerror

Assertion statement (assert) failed

Attributeerror

Attempting to access an unknown object property

Eoferror

User input file End flag EOF (CTRL+D)

Floatingpointerror

Floating-point calculation error

Generatorexit

When the Generator.close () method is called

Importerror

When the import module fails

Indexerror

Index out of range of sequence

Keyerror

Find a keyword that does not exist in the dictionary

Keyboardinterrupt

User input interrupt key (CTRL + C)

Memoryerror

Memory overflow (can free memory by deleting objects)

Nameerror

Try to access a non-existent variable

Notimplementederror

Methods that have not been implemented

OSError

An exception generated by the operating system (for example, opening a file that does not exist)

Overflowerror

Numeric operation exceeds maximum limit

Referenceerror

Weak references (weak reference) attempt to access an object that has been reclaimed by the garbage collection mechanism

RuntimeError

General run-time errors

Stopiteration

There are no more values for iterators

SyntaxError

Syntax error for Python

Indentationerror

Indentation Error

Taberror

Use the tab and Space mix

Systemerror

Python Compiler system error

Systemexit

Python compiler process is closed

TypeError

Invalid operations between different types

Unboundlocalerror

Access an uninitialized local variable (subclass of Nameerror)

Unicodeerror

Unicode-related errors (subclasses of ValueError)

Unicodeencodeerror

Error in Unicode encoding (subclass of Unicodeerror)

Unicodedecodeerror

Error in Unicode decoding (subclass of Unicodeerror)

Unicodetranslateerror

Error in Unicode conversion (subclass of Unicodeerror)

ValueError

Invalid parameter passed in

Zerodivisionerror

Divide by zero

Built-in exception class hierarchy

Baseexception
+--Systemexit
+--Keyboardinterrupt
+--Generatorexit
+--Exception
+--stopiteration
+--Arithmeticerror
| +--Floatingpointerror
| +--Overflowerror
| +--Zerodivisionerror
+--Assertionerror
+--Attributeerror
+--Buffererror
+--Eoferror
+--Importerror
+--Lookuperror
| +--Indexerror
| +--Keyerror
+--Memoryerror
+--Nameerror
| +--Unboundlocalerror
+--OSError
| +--Blockingioerror
| +--Childprocesserror
| +--Connectionerror
|    | +--Brokenpipeerror
|    | +--Connectionabortederror
|    | +--Connectionrefusederror
|    | +--Connectionreseterror
| +--Fileexistserror
| +--Filenotfounderror
| +--Interruptederror
| +--Isadirectoryerror
| +--Notadirectoryerror
| +--Permissionerror
| +--Processlookuperror
| +--Timeouterror
+--Referenceerror
+--RuntimeError
| +--Notimplementederror
+--SyntaxError
| +--Indentationerror
| +--Taberror
+--Systemerror
+--TypeError
+--ValueError
| +--Unicodeerror
| +--Unicodedecodeerror
| +--Unicodeencodeerror
| +--Unicodetranslateerror
+--Warning
+--deprecationwarning
+--pendingdeprecationwarning
+--runtimewarning
+--syntaxwarning
+--userwarning
+--futurewarning
+--importwarning
+--unicodewarning
+--byteswarning
+--resourcewarning

Easygui

Inherited:

Class mylist (list):

Implements the inheritance

Polymorphic

Python's Magic Method:

__init__ (self) Construction method

A function or variable name preceded by two ' _ ' will become private, pseudo-private.

Class Person ():

__name = ' Mengfanchen '

P.__name cannot be called, but P._person__name can be called.

Method overrides can also be made in Python.

Note that the __init__ method is also overridden, and the properties of the parent class can be inherited by writing to the method above.

Python can perform multiple inheritance.

Try to avoid using

The __dict__ method can display all properties and methods of an object.

BIF:

Hasattr (), Getattr (), SetAttr (), delattr ()

Property () method, which enables you to set the operation of an attribute to an attribute.

For example, Del (c1.x) can call Delsize () to remove the Size property.

Construction and destruction

Magic Method:

__init__

The __new__ in this general do not need to be rewritten but when a class inherits from an immutable type (and cannot be __init__) it can be overridden and must have a return value.

The __del__ method is called when the object is destroyed.

Factory function:

If you want the class object to be output with print, you need to override the __str__ method

Override the __repr__ method if you want to directly get the value of the class object

This is useful for calling properties by property.

This is the time to access the property when he calls __getattribute__ and then the related operation, __getattr__ is the method that is called by default when the property of the call is not stored.

The principle of property: the descriptor. Above

Custom containers, if the container is immutable, need to define the __len__ () and __getitem__ () methods.

If mutable, you need to define the __setitem__ () and __getitem () __ methods.

The custom container above is immutable.

Iterators

__iter__ (), __next__ () two magical methods

Generator

Yield generates an iterator

Python Full learning Notes

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.