现在的位置: 首页 > 综合 > 正文

读书笔记

2012年12月11日 ⁄ 综合 ⁄ 共 10591字 ⁄ 字号 评论关闭
  1. Types are associated with objects, not variables. A variable can be assigned a value of any type, and a list can contain objects of many different types.
  2. With Python, you can write a web server to share the files in a directory with just two lines of code

Import http.server

http.server.test(HandlerClass = http.server.SimpleHTTPRequestHandler)

  1. Python’s four number types are integers, floats, complex numbers, and Boolean
  2. Booleans behave like the numbers 1(True) and 0(False)
  3. Keys must be of an immutable type, this includes numbers, strings, and tuples. Values can be any kind of object, including mutable types such as lists and dictionaries.
  4. Functions are defined using the def statement. The return statement is what a function uses to return a value. This value can be of any type. If no return statement is encountered, Python’s None value is returned.
  5. useful ueage for dict.get()

    for word in word_list:

        # increment the occurrences count for this word

        occurs_dict[word] = occurs_dict.get(word, 0) + 1

  1. read returns a string containing all the characters in a file, and split returns a list of the words of a string “split out” based on whitespace
  2. The first argument of any method in a Class is called self. When the method is invoked, self is set to the instance that invoked the method.
  3. None is used to represent an empty value
  4. List is an ordered collection of objects. Python lists can contain different types of elements; a list element can be any Python object
  5. if indices are negative numbers, they indicate positions counting from the end of the list, with -1 being the last position in the list.
  6. list[index1: index2] extract all items including index1 and up to (but not including) index2 into a new list. Leaving out index1 means “go from the beginning of the list”, and leaving out index2 means “go to the end of the list”. Omitting both indices makes a new list that goes from the beginning to the end of the original list; that is, it copies the list.
  7. lista[index1:index2] = listb causes all elements of lista between index1 and index2 to be replaced with the elements in listb. Listb can have more or fewer elements than are removed from lista, in which case the length of lista will be altered.
  8. if you try to append one list to another, the list appended as a single element of the main list
  9. The extend method is like the append method, except that it allows you to add one list to another
  10. list.insert(n, elem) is the same thing as list[n:n] = elem when n is nonnegative.
  11. list.insert(n, elem) as meaning insert elem just before the nth element of list
  12. del list[n] does the same thing as list[n:n+1] = [], whereas del list[m:n] does the same thing as list[m:n] = []
  13. sort changes the list being sorted. To sort a list without changing the original list, make a copy of it first. Soring works with strings too.
  14. The main difference between tuples and lists is that tuples are immutable.
  15. You can create tuples from existing ones by using the + and * operators.
  16. Tuples themselves can’t be modified. But if they contain any mutable objects (lists or dictionaries), these may be changed if they’re still assigned to their own variables. Tuples that contain mutable objects aren’t allowed as keys for dictionaries.
  17. One-element tuples need a comma
  18. Tuples can be easily converted to lists with the list function  (which takes any sequence as an argument and produces a new list with the same elements as the original sequence). Similarly, list can be converted to tuples with the tuple function (which does the same thing but produces a new tuple instead of a new list)
  19. List is a convenient way to break a string into characters
  20. A set in Python is an unordered collection of objects used in situations where membership and uniqueness in the set are main things you need to know about the object. Just as with dictionary keys, the items in a set must be immutable and hashable. This means that ints, floats, strings, and tuples can be members of a set, but lists, dictionaries and sets themselves can't.
  21. Strings are sequences of characters, but strings aren't lists of characters. Unlike lists, strings can't be modified.
  22. Split returns a list of substrings in the string, and join takes a list of strings and puts them together to form a single string with the original string between each element. Typically, splits use whitespace as the delimiter to the strings it's splitting.
  23. Find takes one required argument: the substring being searched for. Find returns the position of the first character of the first instance of substring in the string object, or -1 if substring doesn't occur in the string.
  24. A string is an immutable sequence of Unicode characters, whereas a bytes object is a sequence of integers with values from 0 to 256.
  25. Values in lists are accessed by means of integers called indices, which indicate where in the list a given value is found.
  26. Dictionaries access values by means of integers, strings, or other Python object s called keys, which indicate where in the dictionary a given value is found.
  27. Both lists and dictionaries can store objects of any type.
  28. Word counting

for word in sample_string.split():

                occur[word] = occur.get(word, 0) + 1

  1. Any Python object that is immutable and hashable can be used as a key to a dictionary.
  2. If break is executed, it Immediately terminates the while loop, and not even the post-code will be executed. If continue is executed, it cause the remainder of the body to be skipped over; the condition is evaluated again, and the loop proceeds as normal.
  3. The zip function will take the corresponding elements from one or more iterables and combine them into tuples until it reaches the end of the shortest iterable.
  4. Most Python objects can be used as Booleans, the special Python None is always False. The empty string “” is False, any other string is True. The empty list [] is False, any other list is True. The empty dictionary {} is False, any other dictionary is True. The empty set set() is False, any other set is True.
  5. The == and != operators test to see if their operands contains the same value. The is and is not operators test to see if their operands are the same object.
  6. Arguments are passed in by object reference. The parameter becomes a new reference to the object. For immutable objects (such as tuples, strings, and numbers), what is done with a parameter has no effect outside the function. But if you pass in a mutable object (a list, dictionary, or class instance), any change made to the object will change what the argument is referencing outside the function. Reassigning the parameter doesn’t affect the argument.
  7. A generator function is a special kind of function that you can use to define your own iterators. When you define a generator function, you return each iteration’s value using the yield keyword. When there are no more iterations, an empty return statement or flowing off the end of the function ends the iterations.
  8. Functions are first-class objects in Python, which means that they can be assigned to variables, accessed by way of variables, and decorated.
  9. A namespace is essentially a dictionary of the identifiers available to a block, function, class, and module.
  10. A namespace in Python is a mapping from identifiers to objects and is usually represented as a dictionary. When a block of code is executed in Python, it has three namespaces: local, global, and built-in.
  11. When an identifier is encountered during execution, Python first looks in the local namespace for it. If it isn’t found, the global name space is looked in next. If it still hasn't been found, the built-in namespace is checked. If it doesn't exist there, this is considered an error and a NameError execption occurs.
  12. Absolute pathnames specify the exact location of a file in a filesystem, without any ambiginity;Relative pathnames specify the position of a file relative to some other point in the filesystem.
  13. Python commands may implicitly make use of the current working directory when they’re given a relative path as an argument. If you use os.listdir(path) command with a relative path argument, the anchor for that relative path is the current working directory, and the result of the command is a list of the filenames in the directory whose path is formed by appending the current working directory with the relative path argument.
  14. the constant os.curdir returns whatever string your system happens to use as the same directory indicator. On both UNIX and Windows, this is a single dot; This string is a relative path, meaning that os.listdir will append it to the path for the current working directory, giving the same path.This command returns a list of all the files or folders inside the current working directory. (os.listdir(os.curdir))
  15. The os.path.join function interprets its argument as a series of directory names or filenames, which are to be joined to form a single string understandable as a relative path by the underlying operating system.
  16. In Linux/Unix, an absolute path always begins with a / (because a single slash denotes the topmost directory of the entire system, which contains everything else)
  17. The os.path.split command returns a two-element ruple splitting the basename of a path (the single file or directory name at the end of the path) from the rest of the path.
  18. The os.path.basename function returns only the basename of the path, and the os.path.dirname function returns the path up to but not including the last name.
  19. Toi handle the dotted extension notation used by most filesystems to indicate filetype, Python provides os.path.splitext
  20. os.walk walk through an entire directory tree, returning three things for each directory it travels: the root, or path, of that directory, a list of its subdirectories, and a list of its files.

Import os

For root, dirs, files in os.walk(os.curdir):

    Print(“{0} has {1} files”.format(root, len(files)))

  1. open doesn’t read anything from the file; instead it returns an object called a file object that you can use to access the opened file. A file object keeps track of a file and how much of the file has been read or written. All Python file I/O is done using file objects rather than filenames
  2. Buffering is the process of holding data in memory until enough has been requested or written to justify the time cost of doing a disk access.
  3. Keep in mind that files open in binary mode deal only in bytes, not strings. To use the data as strings, you must decode any bytes objects to string objects.
  4. An exception is an object, it’s generated automatically by Python functions with a raise statement
  5. Each type of exception is a Python class, which inherits from its parent exception type.
  6. Context managers wrap  a block and manage requirements on entry and departure from the block and are marked by the with keyword. File objects are context managers.
  7. All the data types built into Python are classes. __init__() is run every time an instance of the class is created, with that new instance as its first argument. It initialize fileds of the class.
  8. Self is always the name of the first argument of __init__.  Self is set to the newly created instance when __init__ is run,
  9. A class variable is a variable associated with a class, not an instance of a class, and is accessed by all instances of the class. A class variable is created by an assignment in the class body, not in the __init__ function, after it has been created, it can be seen by all instances of the class
  10. A property combines the ability to pass access to an instance variable through methods like getters and setters and the straightforward access to instance variables through dot notation.
  11. When you’re in a method of a class, you have direct access to the local namespace (parameters and variables declared in the method), the global namespace (functions and variables declared at the module level), and the built-in namespace (built-in functions and built-in exceptions)
  12. Private superclass instance variables, private superclass methods, and private superclass class variables can't be accessed using self. A class is able to hide these names from its children.
  13. Python provides automatic memory management through a reference-counting mechanism, that is, it keeps track of the number of references to your instance; when this instance reaches zero, the memory used by your instance is reclaimed, and any Python objects referenced by your instance have their reference counts decremented by one. For the vast majority of your classes, you won't need to define a destructor.
  14. A regular expression is a way of recognizing and often extracting data from certain patterns of text, A regular expression that recognizes a piece of text or string is said to match that text or string.
  15. Types are objects

抱歉!评论已关闭.