- Python programs are executed by an interpreter.
- When you use Python interactively, the special variable _ holds the result
of the last operation.
- 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.
- A newline terminates each statement.
- 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.
- Python does not have a special switch or case statement for testing
values.
- 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.
- File objects support a write() method that can be used to write raw
data.
- Strings are stored as sequences of characters indexed by integers,
starting at zero.
- 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.
- Strings are concatenated with the plus (+) operator.
- Python never implicitly interprets the contents of a string as numerical
data.
- To perform mathematical calculations, strings first have to be converted
into a numeric value using a function such as int() or float().
- Non-string values can be converted into a string representation by using
the str(), repr() or format() function.
- 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.
- Lists are sequences of arbitrary objects. You create a list by enclosing
values in square brackets.
- Lists are indexed by integers, starting with zero. Use the indexing
operator to access and modify individual items of the list
- To append a new items to the end of a list, use the append() method.
- To insert an item into the middle of a list, use the insert() method.
- You can extract or reassign a portion of a list by using the slicing
operator.
- 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
- You create a tuple by enclosing a group of values in parentheses
- The contents of a tuple cannot be modified after creation
- The split() method of strings splits a string into a list of fields
separated by the given delimiter character.
- A set is used to contain an unordered collection of objects. To create a
ser, use the set() function and supply a sequence.
- Unlike lists and tuples, sets are unordered and cannot be indexed by
numbers. Moreover, the elements of a set are never duplicated.
- A dictionary is an associative array or hash table that contains objects
indexed by keys.
- One caution with range() is that in Python 2, the value it creates is a
fully populated list with all if the integer values.
- The object created by xrange() computes the values it represents on demand
when lookups are requested.
- 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.
- 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
- Instead of returning a single value, a function can generate an entire
sequence of results if it uses the yield statement.
- 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
- 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.
- 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.
- 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
- 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.
- The class statement is used to define new types of objects and for
object-oriented programming.
- 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.
- Methods with leading and trailing double underscores are special
methods.
- All of the methods defined within a class apply only to instances of that
class (that is, the objects that are created)
- The import statement creates a new namespace and executes all the
statements in the associated .py file within that namespace
- In Python 2 string literals correspond to 8-bit character or byte-oriented
data.
- Raw strings cannot end in a single backslash, such as r”\”
- 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 -*-
- 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.
- 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.
- 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.
- 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.
- 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.
- The built in function type() returns the type of an object.
- 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
- An object’s reference count is decreased by the del statement or whenever
a reference goes out of scope (or is reassigned)
- When an object’s reference count reaches zero, it is
garbage-collected.
- 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.
- 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.
- A deep copy creates a new object and recursively copies all the objects it
contains.
- All objects in Python are said to be “first class”. This means that
objects that can be named by an identifier have equal status.
- 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.
- 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.
- 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.
- 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.
- Callable types represent objects that support the function call
operation.
- Methods are functions that defined inside a class definition. There are
three common types of methods----instance methods, class methods, and static
methods
- 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.
- 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.
- 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.
- Both instance and class methods are represented by a special object of
type types.MethodType.
- 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.
- When you define a class, the class definition normally produces an object
of type type.
- When an object instance is created, the type of the instance is the class
that defined it.
- The module type is a container that hold objects loaded with the Import
statement.
- Code objects represent raw byte-compiled executable code, or bytecode, and
are typically returned by the built-in compile() function.
- 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.
- __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.
- 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.
- 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,
- The with statement allows a sequence of statements to execute under the
control of another object known as a context manager.
- 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 (==)
- 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.
- 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.
- 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.
- Exception indicate errors and break out of the normal control flow of a
program. An exception is raised using the raise statement.
- To catch an exception, use the try and except statement
- 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.
- The finally statement defines a cleanup action for code contained in a try
block.
- 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.
- 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.
- Default parameter values are always set to the objects that were supplied
as values when the function was defined.
- A function can accept a variable number of parameters if an asterisk(*) is
added to the last parameter name
- Function arguments can also be supplied by explicitly naming each
parameter and specifying a value. These are known as keyword arguments.
- When a function is invoked, the function parameters are simply names that
refer to the passed input objects.
- 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.
- 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.
- 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.
- 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.
- When variables are assigned inside a function, they’re always bound to the
function’s local namespace.
- 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.
- 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
- A decorator is a function whose primary purpose is to wrap another
function or class.
- 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.
- 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.
- A generator expression is an object that carries out the same computation
as a list comprehension, but which iteratively produces the result.
- Anonymous functions in the form of an expression can be created using the
lambda statement.
- 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).
- It’s important to note that a class statement by itself doesn’t create any
instances of the class.
- 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.
- 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.
- 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.
- 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.
- Object is a class which is the root of all Python objects and which
provides the default implementation of some common methods
- Python supports multiple inheritances.
- Dynamic binding is the capability to use an instance without regard for
its type.
- In a class definition, all functions are assumed to operate on an
instance, which is always passed as the first parameter self.
- 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
- 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.
- 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.
- By default, all attributes and methods of a class are public.
- 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.
- Once created, instances are managed by reference counting. If the
reference count reaches zero, the instance is immediately destroyed.
- A weak reference is a way of creating a reference to an object without
increasing its reference count.
- 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.
- When you create an instance of a class, the type of that instance is the
class itself.
- When you define a class in Python, the class definition itself becomes an
object.
- Any Python source file can be used as a module
- 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.
- Each module defines a variable, __name__, that contains the module
name.
- 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.
- 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.
- For each object, the str() function is invoked to produce an output
string.
- The sys module has a function getsizeof() that can be used to investigate
the memory footprint (in bytes) of individual Python objects.
- Whenever you use the (.) operator to look up an attribute on an object, it
always invokes a name lookup.
- Only class instances, functions, methods, sets, frozen sets, files,
generators, type objects. And certain object types defined in library modules
support weak references.
- If you are generating random numbers in different threads, you should use
locking to prevent concurrent access.
- 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.
- Events are used to communicate between threads.
-
[Python Essential Reference, Fourth Edition (2009)]读书笔记,布布扣,bubuko.com
[Python Essential Reference, Fourth Edition (2009)]读书笔记
原文:http://www.cnblogs.com/bluescorpio/p/3587393.html