zoukankan      html  css  js  c++  java
  • [Python Essential Reference, Fourth Edition (2009)]读书笔记

    1. Python programs are executed by an interpreter.
    2. When you use Python interactively, the special variable _ holds the result of the last operation.
    3. Python is a dynamically typed language where variable names are bound to different values, possibly of varying types, during program execution. The assignment operator simply creates an association between a name and a value.
    4. A newline terminates each statement.
    5. The while statement tests the conditional expression that immediately follows. If the tested statement is true, the body of the while statement executes. The condition is then retested and the body executed again until the condition becomes false.
    6. Python does not have a special switch or case statement for testing values.
    7. The open() function returns a new file object. The readline() method reads a single line of input. Including the terminating newline. The empty string is returned at the end of the file.
    8. File objects support a write() method that can be used to write raw data.
    9. Strings are stored as sequences of characters indexed by integers, starting at zero.
    10. To extract a substring, use the slicing operator s[i:j].  This extracts all characters from s whose index k is in the range I <=k<j. if either index is omitted, the beginning or end of the string is assumed.
    11. Strings are concatenated with the plus (+) operator.
    12. Python never implicitly interprets the contents of a string as numerical data.
    13. To perform mathematical calculations, strings first have to be converted into a numeric value using a function such as int() or float().
    14. Non-string values can be converted into a string representation by using the str(), repr() or format() function.
    15. Str() produces the output that you get when you use the print statement, whereas rep() creates a string that you type into a program to exactly represent the value of an object.
    16. Lists are sequences of arbitrary objects. You create a list by enclosing values in square brackets.
    17. Lists are indexed by integers, starting with zero. Use the indexing operator to access and modify individual items of the list
    18. To append a new items to the end of a list, use the append() method.
    19. To insert an item into the middle of a list, use the insert() method.
    20. You can extract or reassign a portion of a list by using the slicing operator.
    21. Lists can contain any kind of Python object, including other lists. Items contained in nested lists are accessed by applying more than one indexing operation
    22. You create a tuple by enclosing a group of values in parentheses
    23. The contents of a tuple cannot be modified after creation
    24. The split() method of strings splits a string into a list of fields separated by the given delimiter character.
    25. A set is used to contain an unordered collection of objects. To create a ser, use the set() function and supply a sequence.
    26. Unlike lists and tuples, sets are unordered and cannot be indexed by numbers. Moreover, the elements of a set are never duplicated.
    27. A dictionary is an associative array or hash table that contains objects indexed by keys.
    28. One caution with range() is that in Python 2, the value it creates is a fully populated list with all if the integer values.
    29. The object created by xrange() computes the values it represents on demand when  lookups are requested.
    30. When default values are given in a function definition, they can be omitted from subsequent function calls. When omitted, the argument will simply take on the default value.
    31. When variables are created or assigned inside a function, their scope is local. That is, the variable is only defined inside the body of the function and is destroyed when the function returns. To modify the value of a global variable from inside a function, use the global statement
    32. Instead of returning a single value, a function can generate an entire sequence of results if it uses the yield statement.
    33. Any function that uses yield is known as a generator. Calling a generator function creates an object that produces a sequence of results through successive calls to a next() method
    34. The next() call makes a generator function run until it reaches the next yield statement. At this point, the value passed to yield is returned by next(), and the function suspends execution. The function resumes execution on the statement following yield when next() is called again. This process continues until the function returns.
    35. A function can be written to operate as a task that process a sequence of inputs sent to it. This type of function is known as a coroutine and is created by using the yield statement as an expression.
    36. A coroutine is suspend until a value is sent to it using send(). When this happens, that value is returned by the (yield) expression inside the coroutine and is processed by the statements that follow. Processing continues until the next (yield) expression is encountered – at which point the function suspends. This continues until the coroutine function returns or close() is called on it
    37. All values used in a program are objects. An object consists of internal data and methods that perform various kinds of operations involving that data.
    38. The class statement is used to define new types of objects and for object-oriented programming.
    39. Inside the class definition, methods are defined using the def statement. The first argument in each method always refers to the object itself. By convention, self is the name used for this argument. All operations involving the attributes of an object must explicitly refer to the self variable.
    40. Methods with leading and trailing double underscores are special methods.
    41. All of the methods defined within a class apply only to instances of that class (that is, the objects that are created)
    42. The import statement creates a new namespace and executes all the statements in the associated .py file within that namespace
    43. In Python 2 string literals correspond to 8-bit character or byte-oriented data.
    44. Raw strings cannot end in a single backslash, such as r””
    45. It is possible to write Python source code in a different encoding by including a special encoding comment in the first or second line of a Python program:                                                       

    #!/usr/bin/env python

    # -*- coding: UTF-8 -*-

    1. Every piece of data stored in a program is an object. Each object has an identity, a type, and a value. You can view the identity of an object as a pointer to its location in memory.
    2. The type of an object, also known as the object’s class, describes the internal representation of the object as well as the methods and operations that it supports. When an object of a particular type is created, that object is sometimes called an instance of that type. After an instance is created, its identity and type cannot be changed.
    3. If an object’s value can be modified, the object is said to be mutable. If the value cannot be modified, the object is said to be immutable. An object that contains references to other objects is said to be a container or collection.
    4. An attribute is a value associated with an object. A method is a function that performs some sort of operation on an object when the method is invoked as a function. Attributes and methods are accessed using the dot(.) operator.
    5. The built in function id() returns the identity of an object as an integer. This integer usually corresponds to the object’s location in memory.
    6. The built in function type() returns the type of an object.
    7. All objects are reference-counted. An object’s reference count is increased whenever it’s assigned to a new name or placed in a counter such as a list, tuple, or dictionary
    8. An object’s reference count is decreased by the del statement or whenever a reference goes out of scope (or is reassigned)
    9. When an object’s reference count reaches zero, it is garbage-collected.
    10. When a program makes an assignment such as a=b, a new reference to b is created. For immutable objects such as numbers and strings, this assignment effectively creates a copy of b.
    11. Two types of copy operations are applied to container objects such as lists and dictionaries: a shallow copy and a deep copy. A shallow copy creates a new object but populates it with references to the items contained in the original object.
    12. A deep copy creates a new object and recursively copies all the objects it contains.
    13. All objects in Python are said to be “first class”. This means that objects that can be named by an identifier have equal status.
    14. The None type denotes a null object (an object with no value). Python provides exactly one null object, which is written as None in a program. This object is returned by functions that don't explicitly return a value.
    15. Sequences represent ordered sets of objects indexed by non-negative integers and include strings, lists, and tuples. Strings are sequences of characters, and lists and tuples are sequences of arbitrary Python objects. Strings and tuples are immutable; lists allow insertion, deletion, and substitution of elements. All sequences support iteration.
    16. A mapping object represents an arbitrary collection of objects that are indexed by another collection of nearly arbitrary key values. Unlike a sequence, a mapping object is unordered and can be indexed by numbers, strings, and other objects. Mapping are mutable.
    17. A set is an unordered collection of unique items. The items placed into a set must be immutable. Set is a mutable set, and frozenset is an immutable set.
    18. Callable types represent objects that support the function call operation.
    19. Methods are functions that defined inside a class definition. There are three common types of methods----instance methods, class methods, and static methods
    20. An instance method is a method that operates on an instance belonging to a given class. The instance is passed to the method as the first argument, which is called self by convention.
    21. A class method operates on the class itself as an object. The class object is passed to a class method in the first argument, cls.
    22. A static method is a just a function that happens to be packaged inside a class. It does not receive an instance or a class object as a first argument.
    23. Both instance and class methods are represented by a special object of type types.MethodType.
    24. Class objects and instances also operate as callable objects. A class object is created by the class statement and is called as a function in order to create new instances.
    25. When you define a class, the class definition normally produces an object of type type.
    26. When an object instance is created, the type of the instance is the class that defined it.
    27. The module type is a container that hold objects loaded with the Import statement.
    28. Code objects represent raw byte-compiled executable code, or bytecode, and are typically returned by the built-in compile() function.
    29. Generator objects are created when a generator function is invoked. A generator function is defined whenever a function makes use of the special yield keyword. The generator object serves as both an iterator and a container for information about the generator function itself.
    30. __new__() is a class method that is called to create an instance. The __init__() method initializes the attributes of an object and is called immediately after an object has been newly created. The __new__() and __init__() methods are used together to create an initialize new instances.
    31. The __del__() method is invoked when an object is about to be destroyed. This method is invoked only when an object is no longer in use.
    32. If an object, obj, supports iteration, it must provide a method, obj.__iter__(), that returns an iterator object. The iterator object iter, in turn, must implement a single method, iter.next(), that returns the next object or raises StopIteration to signal the end of iteration,
    33. The with statement allows a sequence of statements to execute under the control of another object known as a context manager.
    34. The equality operator (x==y) tests the values of x and y for equality. In the case of lists and tuples, all the elements are compared and evaluated as true if they’re of equal value. For dictionaries, a true value is returned if x and y have the same set of keys and all the objects with the same key have equal values. Two sets are equal if they have the same elements, which are compared using equality (==)
    35. The identity operators (x is y and x is not y) test two objects to see whether they refer to the same object in memory. In general, it may be the case that x==y, but x is not y.
    36. The while statement executes statements until the associated expression evaluates to false. The for statement iterates over all the elements of s until no more elements are available.
    37. To break out of a loop, use the break statement. To jump to the next iteration of a loop (skipping the remainder of the loop body), use the continue statement.
    38. Exception indicate errors and break out of the normal control flow of a program. An exception is raised using the raise statement.
    39. To catch an exception, use the try and except statement
    40. When an exception occurs, the interpreter stops executing statements in the try block and looks for an except clause that matches the exception that has occurred. If one is found, control is passed to the first statement in the except clause. After the except clause is executed, control continues with the first statement that appears after the try-except block. Otherwise, the exception is propagated up to th e block of code in which the try statement appeared.
    41. The finally statement defines a cleanup action for code contained in a try block.
    42. All the built in exceptions are defined in terms of classes. To create a new exception, create a new class definition that inherits from Exception.
    43. Functions are defined with the def statement. The body of a function is simply a sequence of statements that execute when the function is called. You invoke a function by writing the function name followed by a tuple of function arguments. The order and number of arguments must match those given in the function definition. If a mismatch exists, a TypeError exception is raised.
    44. Default parameter values are always set to the objects that were supplied as values when the function was defined.
    45. A function can accept a variable number of parameters if an asterisk(*) is added to the last parameter name
    46. Function arguments can also be supplied by explicitly naming each parameter and specifying a value. These are known as keyword arguments.
    47. When a function is invoked, the function parameters are simply names that refer to the passed input objects.
    48. If a mutable object(such as a list or dictionary) is passed to a function where it's then modified, those changes will be reflected in the original object.
    49. Functions that mutate their input values or change the state of other parts of the program behind the scenes are said to have side effects.
    50. The return statement returns a value from a function. If no value is specified or you omit the return statement, the None object is returned. To return multiple values, place them in a tuple.
    51. Each time a function executes, a new local namespace is created. This namespace represents a local environment that contains the names of the function parameters, as well as the names of variables that are assigned inside the function body. When resolving names, the interpreter first searches the local namespace. If no match exists, it searches the global namespace. The global namespace for a function is always the module in which the function was defined. If the interpreter finds no match in the global namespace, it makes a final check in the built In namespace. If this fails, a NameError exception is raised.
    52. When variables are assigned inside a function, they’re always bound to the function’s local namespace.
    53. Functions are fist-class objects in Python. This means that they can be passed as arguments to other functions, placed in data structures, and returned by a function as a result.
    54. When the statements that make up a function are packaged together with the environment in which they execute, the resulting object is known as a closure
    55. A decorator is a function whose primary purpose is to wrap another function or class.
    56. If a function uses the yield keyword, it defines an object known as a generator. A generator is a function that produces a sequence of values for use in iteration.
    57. Inside a function, the yield statement can also be used as an expression that appears on the right side of an assignment operator. A function that uses yield is this manner is known as a coroutine, and it executes in response to values being sent to it.
    58. A generator expression is an object that carries out the same computation as a list comprehension, but which iteratively produces the result.
    59. Anonymous functions in the form of an expression can be created using the lambda statement.
    60. A class defines a set of attributes that are associated with, and shared by, a collection of objects known as instances. A class is most commonly a collection of functions(known as methods), variables (which are known as class variables), and computed attributes(which are known as properties).
    61. It’s important to note that a class statement by itself doesn’t create any instances of the class.
    62. The functions defined inside a class are known as instance methods. An instance method is a function that operates on an instance of the class, which is passed as the first argument. By convention, this argument is called self.
    63. Instances of a class are created by calling a class object as a function. This creates a new instance that is then passed to the __init__() method of the class. The arguments to __init__() consist of the newly created instance self along with the arguments supplied when calling the class object.
    64. Inheritance is a mechanism for creating a new class that specializes or modifies the behavior of an existing class. The original class is called a base class or a superclass.
    65. When a class is created via inheritance, it “inheritance” the attributes defined by its base class. However, a derived class may redefine any of these attributes and add new attributes of its own.
    66. Object is a class which is the root of all Python objects and which provides the default implementation of some common methods
    67. Python supports multiple inheritances.
    68. Dynamic binding is the capability to use an instance without regard for its type.
    69. In a class definition, all functions are assumed to operate on an instance, which is always passed as the first parameter self.
    70. A static method is an ordinary function that just happens to live in the namespace defined by a class. It doesn't operate on any kind of instance. To define a static method, use the @staticmethod decorator
    71. Class methods are methods that operate on the class itself as an object. Defined using the @classmethod decorator, a class method is different than an instance method in that the class is passed as the first argument which is named cls by convention.
    72. Normally, when you access an attribute of an instance or a class, the associated value that is stored is returned. A property is a special kind of attribute that computes its value.
    73. By default, all attributes and methods of a class are public.
    74. Giving a method a private name is a technique that a superclass  can use to prevent a derived class from redefining and changing the implementation of a method.
    75. Once created, instances are managed by reference counting. If the reference count reaches zero, the instance is immediately destroyed.
    76. A weak reference is a way of creating a reference to an object without increasing its reference count.
    77. Internally, instances are implemented using a dictionary that’s accessible as the instance’s __dict__ attribute. This dictionary contains the data that’s unique to each instance.
    78. When you create an instance of a class, the type of that instance is the class itself.
    79. When you define a class in Python, the class definition itself becomes an object.
    80. Any Python source file can be used as a module
    81. Modules are first class objects in Python. This means that they can be assigned to variables, placed in data structures such as a list, and passed around in a program as a data.
    82. Each module defines a variable, __name__, that contains the module name.
    83. When loading modules, the interpreter searches the list of directories in sys.path. the first entry in sys.path is typically an empty string ‘’, which refers to the current working directory.
    84. When Python starts, command-line options are placed in the list sys.argv.  the first argument is the name of the program. Subsequent items are the options presented on the command line after program name.
    85. For each object, the str() function is invoked to produce an output string.
    86. The sys module has a function getsizeof() that can be used to investigate the memory footprint (in bytes) of individual Python objects.
    87. Whenever you use the (.) operator to look up an attribute on an object, it always invokes a name lookup.
    88. Only class instances, functions, methods, sets, frozen sets, files, generators, type objects. And certain object types defined in library modules support weak references.
    89. If you are generating random numbers in different threads, you should use locking to prevent concurrent access.
    90. A running program is called a process. Each process has its own system state, which includes memory, lists of open files, a program counter that keeps track of the instruction being executed, and a call stack used to hold the local variables of functions.
    91. Events are used to communicate between threads.
    92.  
  • 相关阅读:
    SDOI2019游记
    noi.ac309 Mas的童年
    51nod1237 最大公约数之和
    loj6074 子序列
    noi.ac89A 电梯
    51nod97B 异或约束和
    bzoj4490 随机数生成器Ⅱ加强版
    CF55D Beautiful numbers
    CF24D Broken robot
    CF226D The table
  • 原文地址:https://www.cnblogs.com/bluescorpio/p/3587393.html
Copyright © 2011-2022 走看看