C ++ programmer Python notes

Source: Internet
Author: User

1. important getchas: judge whether a object is a type (object) = type (str () or from types import StringTypes type (object) = types. stringType # Remember to import types or if isinstance (obj, StringTypes): use is as much as possible as the system-defined single value. Although = can use the same function, it is much less efficient, one is to directly compare a comparison function that needs to be called, which has been tested by foreigners. For example, if x is None, if x is not None, and if x = None. Is not. All control statements must use ':' To wrap and define functions. Remember, everything in Python is an object, including a function. Try to use xrange instead of range. range directly generates a list of the specified size, while xrange only generates an object and generates the next value as needed, which saves a lot of memory, using range for values that are large enough may result in insufficient memory. Code specification: the first letter of the class name is uppercase, e.g ., dog, the variable and function name__ start with private, try to expose the function to the external, the variable name can be lowercase and _, the same as Linux. In some cases, the name conflict with the system can end with "_ china _. Http://www.cnblogs.com/kym/archive/2011/03/17/1986640.html2. the itertools module is very effective for iteration and combination, for example, import itertools iter = itertools. permutations ([1, 2, 3]) lst = list (iter) # in this case, the lst is in the full arrangement of [1, 2, 3. an array is a list. The colon in the subscript indicates that a single item in the string starting from XX or XX cannot be modified, therefore, you cannot use str_test [5] = 'M' to modify a byte. The correct method is str_test = str_test [4:] + 'M' + str_test [: 6] But this method will copy the string multiple times, resulting in low efficiency. Therefore, it is better to store the string with list and then convert it to the length instead of list. len is len (list) 4. details about sequence slice For example, string, list, And tuple 1) + cannot be used to connect a string and number, because it is also a Number Addition operator 2) [] except that the start and end values represent the start and end positions, the last one represents step value 5. python data type classification number sequence: string (immutable), list, tuple (immutable) mapping: dictionary, similar to map variable and immutable in stl, similar to const in c ++, that is, once defined, the value cannot be changed. Number supports various arithmetic operations. String is ordered and unchangeable. List is ordered and variable. Dictrionary is unordered, and variable tuple is ordered and unchangeable. Str () list () dict () tuple () built-in functions are used to construct the corresponding types respectively. 6. list features: ordered and variable sequences can be directly constructed using list. For example, when test_list = list ('China') is modified, it can be directly set to slice, the replaced content is not required to have the same length as the new content. Therefore, the length of the list may change after modification, for example, test_list [] = ['n', 'A ', 'M', 'mddd'] Or test_list [4:] = ['E'] note that the count in the list is not the number of elements, the number of times the given value appears in the list is as follows: >>> L. append (4) # Only one object can be added at a time and cannot be used for two sequence connections, because the new sequence will be added as an object >>> L [0, 1, 2, 3, 4]> L. extend ([5, 6]) # Add the parameter to the end of a sequence> L [0, 1, 2, 3, 4, 5, 6] >>> L = L + [7] # Can Be sequence or object. The difference is that a new object is constructed, so a value must be assigned again, as for whether + = will be processed as append or extend, there is no relevant information at present. If the author notices this kind of optimization, it should be done> L [0, 1, 2, 3, 4, 5, 6, 7] 7. the dictionary initialization method is test_dic = {1: 'one', 2: 'Two}. You can use items () to export it to list, test_list = test_dic.items (), A list similar to [(1, 'one'), (2, 'two')] is obtained. You can use fromkeys () to import the key from the list. The value is filled with None, for example, test_list = [1, 2, 3, 4] test_dic.fromkeys (test_list) for x in test_dic traverses test_dic, and keys are traversed by default. iterkeys (), itervalues (), and iteritems () of test_dic can be used to obtain iterator for Traversing keys, values, and items respectively. 8. tuple test_tuple = (1, 3, 4) tuple can be interpreted as a const list, but its members are variable, that is, a certain position of the object must point to a certain object and cannot point to another object, but the object itself is variable. Note that when there is only one initial member, you need to add ',' At the end of the initialization, for example, test_tuple = (1,). Otherwise, it will be initialized as an integer. 9. check whether a value in the container uses in instead of index and whether the returned value is greater than 0... 10. print a, B, c, and print automatically add a space after each variable, and end with a comma to prevent the \ n linefeed print> object, x, y exports x and y to the write method of the object. This ojbect must have some methods. In Python, print is the abbreviation of the following statement: import sys. stdout. write (str (x) + '\ n'). Therefore, you can implement the print Output redirection function by redirecting stdout. import sys fp = file('log.txt', 'A') sys. stdout = fp print 'Hello world! Heihei'sys. stdout = sys. _ stdout _ # reset to default11. to write more than one line of statements and syntax Python, a pair of symbolic statements or '\' must be added to the previous line, which is the same as C, the second method is not recommended, because () can be used in any case to replace switch/case in Python with multiple if/elif/else, alternatively, you can use dictionary to combine lambda expressions, such as: choice = 'inc' g = {'inc': lambda x: x + 1, 'dec ': lambda x: the while and for clauses in x-1} g [choice] (x) Python can contain else clauses. Note that break does not jump to else. Only the loop judgment Expression is False. 12. map (function, seq1, seq2 ,...) call the function for each of the seq items in the seq list, and construct the list of return values. If functon is None, the map (lambda x, y: y/x, time, ratio) # The average ratio13. zip at each time point is to combine two arrays x = [1, 2, 3, 4, 5] y = [6, 7, 8, 9, 10] zip (x, y) Returns [(1, 6), (2, 7), (3, 8), (4, 9 ), (5, 10)] For example, if you have two sets of coordinates and you want to add them to each other, the zip function is very useful. For example, you have two arrays, A, B, and A, which store the names of the persons in the class. B is the test score of each person, you need to query the test scores by a person's name. You need a dictionary. zip can help you easily create a dictionary: >>> x = ['bob ', 'Tom ', 'Kitty'] >>> y = [80, 90, 95] >>> d = dict (zip (x, y) [('bob ', 80), ('Tom ', 90), ('Kitty', 95)]> d ['bob'] returns 80, which is convenient. 14. all objects in Python are objects, and functions are no exception. Def defines a function object. The defined object can be assigned a value. The same applies to lambda functions. If x = 0: def npower (n): x ** 2 else: def npower (n): x ** 3 nload = npowernload (5) L = [npower, nload] 15. namespace 1: assign values (including explicit and implicit values) generate identifiers. The location of the assignment determines the namespace in which the identifiers reside. Second, function definitions (including def and lambda) generate new namespaces. Third, the sequence for searching an identifier in python is "LEGB ". The so-called "LEGB" is the abbreviation of the first letter of the English name of the four-layer namespace in python. The innermost layer is L (local), which indicates that it is in a function definition and does not include the function definition in this function. The second layer E (enclosing function) is represented in a function definition, but this function also contains the function definition. In fact, the L layer and the E layer are only opposite. Level 3G (global) refers to the namespace of a module, that is, the identifier defined in A. py file, but not in a function. Layer-4 B (builtin) refers to the namespace that the python interpreter already has at startup, builtin is called because the python interpreter automatically loads the _ builtin _ module when it is started. The list, str, and other built-in functions in this module are in the namespace of layer B. In fact, you only need to pay attention when programming. Do not use the same identifier. Basically, you can avoid any problems related to namespaces. In addition, try not to use the identifiers in the upper namespace in a function. If you must use the identifiers in the upper namespace, it is best to use the parameter transfer method, which is conducive to maintaining the independence of the function. 16. function parameter passing method keyword Assignment Method: Unlike C/C ++, the order of the form parameters can be changed according to the sequence of passing parameters, for example, F (arg2 = 2, arg1 = 1) F (arg1, arg2 ,...) F (arg2 = <value>, arg3 = <value> ...) # function definition with default values. If the parameter with the default value needs to be prefixed, use the keyword value assignment method F (* arg1) # No matter how many parameters are stored in the "F (** arg1)" Field of the tuple named identifier # No matter how many parameters are stored in the dictionary named identifier, when the call is performed in a format similar to F (x = 1, y = 2), arg1 = {('x': 1), ('y': 2)} 17. lambda functions are different from C ++. lambda can only be a row in Python and can use ';', but cannot use for/while/if, although some techniques can be used for implementation, it is not recommended that the map, reduce, and filter functions provided by the system Easy to use. Lambda x, y: x + y; print x, y; x + y + 118. class-related constructor of the _ init _ (self) class. If passing parameters can be written as _ init _ (self, arg1, arg2 ...), similar to bind in c ++. Destructor of the _ del _ (self) Class _ call _ (self, arg1 ,...) the permissions in the operator classes similar to the overload brackets in C ++ are fully differentiated by _ and _, that is, the directly named public function derived class needs to manually call the base class _ init __, otherwise, the inheritance class Animal (object): name = 'unname' # member varieble def _ init _ (self, voice = 'hello', name = 'default '): self. voice = voice print 'animal ::__ init __, name: ', name def _ call _ (self, voice) self. voice = voice def say (self): print self. voice print self. name class Dog (Animal): def _ init _ (self): # Animal. _ init _ (self) # manually call super (Dog, self ). _ init _ () # Replace self. dogName = 'domainname' Dog dd ('wangwang') # invoke _ call _ d. say ()

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.