Python Core Programming summary

Source: Internet
Author: User
Tags integer numbers shallow copy python script
First, Quick start1, Python does not support the C language of self-increase and self-reduction operations 2, the Python string has its own index: The index of the first character is 0, and the last character's index is-1 3, the PRINT statement defaults to adding a newline character to each line, as long as you add a comma at the end of the print statement, You can change its behavior.
Second, Python basics1, each Python script file can be used as a module, the module in the form of disk files. 2. Python assignment is not a value assigned to a variable, the object is passed by reference. 3, Python does not support prefixes, suffix of the self increase, since minus 4, Python does not support overloaded identifiers, so at any time only one name binding 5, Python import the required modules, each module import once, when the function inside the module import code will not be executed, unless the function is executing 6, If the module is imported, the __name__ value is the module name, and if the module is executed directly, the __name__ value is ' __main__ '
three, Python basics1, for the same object identity (see blog) 2, the STR () function gets the string readable, and the repr () function gets a string that can often be used to regain the object, which is usually the case for obj = = eval (repr (obj)), and Str is not. But remember that it is not the Repr object that is able to regain the prototype of this pair through eval. 3, a type that can hold a single literal object we call atomic or scalar storage, those types that can hold multiple objects, we call container storage (composite objects), and these containers can hold different types of objects. 4, the type is variable variable type: list, dictionary immutable type: number, string, tuple (variable or variable whether the ID is the same after change) 5, Python does not support character types, only String type 6, Access classification direct access: Numeric sequential access: string, list, tuple mapping access: Dictionary
Iv. Digital1, delete a reference to the Object Del Method 2, Python's long Integer and C language or other compiled languages, the value can be expressed only with the size of the virtual memory supported by your machine
v. Sequence: strings, lists, and tuples1. The original string is intended to deal with those special characters that appear in the string. In the original string, all characters are directly installed literal meaning to use, do not transfer special or cannot print characters. 2. The original string is simply a ' r ' before the first quotation mark and can be capitalized. 3, CHR return function of the corresponding ASCII characters, and Ord the opposite 4, string.find and String.index difference is not found the Find function will return a-1 value, and index will return an exception 5, Triple quotes Let programmers free from the mire of quotes and special strings, keeping a small string in the form of what is called the WYSIWYG format. 6, the string is immutable, so the string of a character or a character changes are not allowed 7, the Python standard library inside most of the modules are compatible with Unicode, in addition to pickle Module 8, general use Extend () method to add the contents of a list to another list instead of the join operator. The Extend method does not re-establish a new list 9, the list type has its own method, like the connection operation, the list can be constructed--list parsing 10, the list is sorted by sorted, the sort uses a dictionary order, Rather than the alphabetic (literal ' T ' ASCII code value is more than the literal ' a ') 11, boredom is a list or tuple can not be completely converted, a tuple list object can not become a tuple, and you pass to the list of objects can not really become a list, Although the two objects have the same set of data (so equals = =), the variable is not pointing to the same object (the is operation returns false). 12, using index () to check whether an element exists in a list is not a good idea, because we are wrong, you should first check with the in member relation operator, and then use Index () to find the location of this element. 13. The method of changing objects that can change the value of an object is a 14 that has no return value, and a tuple of only one element needs to be added with a comma (,) in the tuple delimiter to prevent confusion with the normal grouping operator in [*]: Ktuple = (' a ',)

In [to]: type (ktuple)
OUT[87]: <type ' tuple ' >

In [a]: Ktuple = (' a ')

In [$]: type (ktuple)
OUT[89]: <type ' str ' > 15, because the tuple is immutable, so there is no way to separate the elements of a tuple, of course, you can discard unwanted elements after the formation of a tuple is no problem. To display the deletion of an entire tuple, simply reduce the object reference count with the DEL statement. When the reference count reaches 0, the object is destructor 16, because tuples are immutable, sorting, replacing, adding is superfluous for tuple operations, these methods are not implemented 17, the tuple object itself is immutable, but this does not mean that the tuple contains Mutable objects that are immutable When an element within a tuple is a list, it can be changed in [$]: print Atuple
--------> Print (atuple)
(123, ' abc ', [' a '], [' A ', ' B '])

in [[]: atuple[3][0] = ' d '

In [Atuple]:
OUT[105]: (123, ' abc ', [' a '], [' d ', ' B '] 18, a shallow copy of a sequence type object is a default type copy and can be implemented in several ways: (1) Full slice operation [:] (2) Use of factory functions, such as List (), Dict (), etc. (3) The copy function of copy Module 19, deep Copy to take the Copy.deepcopy () function 20, about the operation of the copy warning: first, non-container types (such as numbers, strings, and other atomic types of objects, like code, Types and Xrange objects, etc.) are not copied. A shallow copy is done with a full switching operation. Second, if the tuple variable contains only an atomic type object, a deep copy of it will not proceed.
sixth chapter mappings and collection Types1, using the Factory Method Dict () to create a dictionary or use the built-in method (version 2.3) Fromkeys () to create a "default" Dictionary 2, built-in Method update () adds the entire contents of the dictionary to another dictionary 3, the dictionary can work with all the standard type operators, But it does not support such operations as stitching and repeating. 4, Dictionary size algorithm comparison: The first is the size of the dictionary, then the key, and then the value, if all the same, think the two equal 5, the dictionary elements are not in order, the output is not the same as you entered 6, lists and dictionaries such a mutable type is not hashed, can not be a key value ; All immutable types are hash-able. Values equal to the same key, that is, integer numbers and floating-point numeric values are the same, in which they are the same key value; The tuple is immutable, but it is not immutable, so it is necessary to make a valid key value for the tuple, which can only contain immutable parameters such as numbers and strings. 7. There are two different types of collections: Variable set (set) and immutable set (Frozenset) 8, if the left and right two operands are of the same type, many are variable sets or mutable sets, the resulting demerit types are the same, and if not the same, generate the left operation type 9,
seventh chapter conditions and circulation
eighth chapter documents and input and output1, the file is only a contiguous sequence of bytes, the transmission of data is often used to stream bytes, regardless of whether the byte stream consists of 2 of individual or large chunks of data, and when the input method such as read () or readlines () reads a row from a file, Python does not delete the line terminator, which is left to the programmer , instead of using the write () or writelines () output will not automatically join the line terminator, the programmer should complete the 3, text () method is to the Seek () method supplement, tell you the current file pointer in the file position 4, write and writelines difference. 5, Python provides two modules to assist in processing command-line parameters, the original module getopt module simpler, but not very fine, and optparse more powerful, and object-oriented, if the simple option to use getopt, complex words in the use of Optparse
nineth Chapter Errors and anomalies1, can be in a except clause to handle multiple exceptions, except statements in handling multiple exceptions required to be placed in a tuple 2, if you determine the need to catch all the exceptions, then use the new Baseexception 3, The code in finally throws another exception or terminates due to return, break, continue syntax, and the original exception is lost and cannot be raised again
the tenth chapter functions and Function-type programming1. Many statically typed languages argue that the type of a function is the type of its return value. In Python, because Python is dynamically determining types and functions can return different types of values, so there is no direct Type Association 2, all objects are passed by reference, function is no exception, when a variable assignment, the actual is to assign the same object reference to the variable 3, Functions can be passed as arguments to other functions to call 4, use the * and * * symbols in function calls to specify the elements of tuples and dictionaries as non-keywords and keyword parameters method 5, you can create PFA by using the partial () function in the functional module (partial function) be wary of keywords6. If the name of the global variable is declared in a function body, the name of the global variable can be overwritten by the local variable. So at this point you want to declare 7 with the global statement, in the version before 2.1, up to two scopes: local scope and global scope of a function, although nesting of multiple functions, but no access to more than two scopes 8, closures are more appropriate for a callback function that must have its own scope. In particular, the callback function is very small and simple 9, [Root@aa python]# cat my_lambda.py
#!/usr/bin/env python

x = 10
def foo ():
y = 5
Bar = Lambda Y=y:x + y
Print Bar ()
y = 8
Print Bar ()

Foo () [Root@aa python]# python my_lambda.py
15
15 is because the value of the outer y is passed in and set in the lambda, so although its value changes later, the definition of the lambda does not change, and the alternative is to add a local variable Z [root@aa python]# that references the function's local variable y in a lambda expression. Cat my_lambda.py
#!/usr/bin/env python

x = 10
def foo ():
y = 5
Bar = Lambda Z:x + Z
Print bar (y)
y = 8
Print bar (y)

Foo ()
The above is for the previous version of 2.1 only need to do so, 2.1 later version because of support can access more than two Fish 3 no need to do so, directly write[Root@aa python]# Cat my_lambda.py
#!/usr/bin/env python

x = 10
def foo ():
y = 5
Bar = lambda:x + y
Print Bar ()
y = 8
Print Bar ()

Foo ()
11th Chapter 1, when accessing a property, the interpreter must find it in one of the three namespaces, starting with the local namespace, and if it is not found, the interpreter will continue to look for the global namespace, and if it fails, it will look in the built-in namespace. 2. Module Import order Python standard library module Python third party module application custom Module 3, if you import at the top of a module, its scope is global and if you import in a function, its scope is local 4, a module is only loaded once, no matter how many times it is imported 5, Python implements the __FUTURE__ directive, allowing programmers to prepare for new things. from __future__ import new_feature; only import_future__ will not change anything, so this is forbidden. (In fact this allows, but it won't be as you want to enable all features) you must display the import of the specified feature 6, reload () built-in function can re-import a module that has already been imported, the module must be imported, and must be imported successfully. The parameter of the function must be a string of the module itself rather than the heroic module name. 7, the import statement is always absolute import, so the relative import applies only to the From-import statement
12th Chapter Object-oriented Programming1. All new classes must inherit at least one parent class, which can be one (single inheritance) or multiple (multiple inheritance) to inherit the parent class. 2, object is "the mother of all classes", if your class does not have heirs and other parent classes, Boject will be the default parent class. 3, Python Strict requirements, there is no instance, the method can not be invoked. This qualification is the binding 4 that Python describes, the properties of the view class, the simplest practical dir () built-in function, and by accessing the class dictionary property __dict__, which is one of the special attributes that all classes have 5, __init__ () should return none, if the constructor is defined, It should not return any objects, because the instance object is automatically returned after the instantiation call. 6, the instance has only two special properties: i.__class__ instantiation I of the class i.__dict__ I of the property 7, __dict__ property consists of a dictionary, contains all the properties of an instance, the key is the property name, the value is the corresponding data value of the property. There are only instance properties in the dictionary, no class attributes or special properties 8, the class can be used to access class properties, if the instance does not have the same name of the property, can also be used to access the instance; If the class property is variable, the property is modified by an instance, and the properties of the class9. A method can be invoked only if it has an instance of the class it belongs to, and when there is an instance, the method is considered bound to that instance. 10, Staticmethod () and Classmethod () built-in functions create static methods and class method 11, document strings for classes, functions/ The method and the module are all unique. Will not be inherited 12, Error when calling the Metaclass bases cannot create a consistent method resolution
Order (MRO) for bases
13, overriding __init__ does not automatically call the base class's __init__ 14, multiple inheritance has two aspects to remember: first, find the right attribute, and when you rewrite the method, how to invoke the corresponding parent class method to "play their role" 15, classical class, using depth first algorithm, Because the new class inherits from object, and the newer diamond class inherits the structure, the problem goes on, so you have to create a new MRO
Chapter 13th Implementation Environment1, when the user enters a list is, Raw_input () returns a list string description, and input () returns the actual list
14th Chapter Regular Expressions1, match is an attempt to match from the beginning of the string, and search is from the left to the right to carry out searching matches
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.