第129页 chapter 1- chapter 6 Decorator
囧囧的心情 (多读书,多思考)
- 章节名:chapter 1- chapter 6 Decorator
- 页码:第129页
先喷下那些喜欢喷翻译版的,有本事鄙视人家就没本事自己去看英文版啊?网上这么多电子英文版。2B。 CHAPTER 1 1. Triple-quoted strings are useful when the contents of a string literal span multiple lines of text such as the following: print '''Content-type: text/html <h1> Hello World </h1> Click here. ''' 2. >>> x = 3.4 >>> str(x) '3.4' >>> repr(x) '3.3999999999999999' >>>format(x,"0.5f") '3.40000' >>> 3. >>> i = [0,1,2,3,4,5] >>> i[0:2] [0, 1] ==> Notice it acts like range.. Not 0, 1, 2 4. Tuples CANNOT be modified after creation in contrast to Lists Tuples are much more environmental friendly than Lists => less memory consumption 5.To change the file object’s position, use f.seek(offset, from_what). The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point. >>> >>> f = open('workfile', 'r+') >>> f.write('0123456789abcdef') >>> f.seek(5) # Go to the 6th byte in the file >>> f.read(1) '5' >>> f.seek(-3, 2) # Go to the 3rd byte before the end >>> f.read(1) 'd' 6. static method -> @staticmethod CHAPTER 2 LEXICAL CONVENTIONS AND SYNTAX 1. Each statement in a program is terminated with a newline. Long statements can span multiple lines by using the line-continuation character (\), as shown in the following example: a = math.cos(3 * (x - n)) + \ math.sin(3 * (y - n)) 2. Table 2.1 Standard Character Escape Codes Character Description \ Newline continuation \\ Backslash \' Single quote \" Double quote \a Bell \b Backspace \e Escape \0 Null From the Library of Lee Bogdanoff Download at WoweBook.Com 28 Chapter 2 Lexical Conventions and Syntax Table 2.1 Continued Character Description \n Line feed \v Vertical tab \t Horizontal tab \r Carriage return \f Form feed \OOO Octal value (\000 to \377) \uxxxx Unicode character (\u0000 to \uffff) \Uxxxxxxxx Unicode character (\U00000000 to \Uffffffff) \N{charname} Unicode character name \xhh Hexadecimal value (\x00 to \xff) 3. ^ => XOR operator 4. Source Code Encoding 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 -*- s = "Jalapeño" # String in quotes is directly encoded in UTF-8. When the special coding: comment is supplied, string literals may be typed in directly using a Unicode-aware editor. However, other elements of Python, including identifier names and reserved words, should still be restricted to ASCII characters. CHAPTER 3 TYPES AND OBJECTS 1. # Compare two objects def compare(a,b): if a is b: # a and b are the same object statements if a == b: # a and b have the same value statements if type(a) is type(b): # a and b have the same type statements 2. The current reference count of an object can be obtained using the sys.getrefcount() function. For example: >>> a = 37 >>> import sys >>> sys.getrefcount(a) 7 >>> 3. IMPORTANT -> COPY 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. Here’s an example: >>> a = [ 1, 2, [3,4] ] >>> b = list(a) # Create a shallow copy of a. >>> b is a False >>> b.append(100) # Append element to b. >>> b [1, 2, [3, 4], 100] >>> a # Notice that a is unchanged [1, 2, [3, 4]] >>> b[2][0] = -100 # Modify an element inside b >>> b [1, 2, [-100, 4], 100] >>> a # Notice the change inside a [1, 2, [-100, 4]] >>> In this case, a and b are separate list objects, but the elements they contain are shared. Therefore, a modification to one of the elements of a also modifies an element of b, as shown. A deep copy creates a new object and recursively copies all the objects it contains. There is no built-in operation to create deep copies of objects. However, the copy.deepcopy() function in the standard library can be used, as shown in the following example: >>> import copy >>> a = [1, 2, [3, 4]] >>> b = copy.deepcopy(a) >>> b[2][0] = -100 >>> b [1, 2, [-100, 4]] >>> a # Notice that a is unchanged [1, 2, [3, 4]] >>> 4. COMPLEX NUMBER Complex numbers are also supported; imaginary numbers are written with a suffix of "j" or "J". Complex numbers with a nonzero real component are written as "(real+imagj)", or can be created with the "complex(real, imag)" function. >>> 1j * 1J (-1+0j) >>> 1j * complex(0,1) (-1+0j) >>> 3+1j*3 (3+3j) >>> (3+1j)*3 (9+3j) >>> (1+2j)/(1+1j) (1.5+0.5j) Complex numbers are always represented as two floating point numbers, the real and imaginary part. To extract these parts from a complex number z, usez.real and z.imag. >>> a=1.5+0.5j >>> a.real 1.5 >>> a.imag 0.5 The conversion functions to floating point and integer (float(), int() and long()) don't work for complex numbers -- there is no one correct way to convert a complex number to a real number. Use abs(z) to get its magnitude (as a float) or z.real to get its real part. >>> a=1.5+0.5j >>> float(a) Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: can't convert complex to float; use e.g. abs(z) >>> a.real 1.5 >>> abs(a) 1.58113883008 5. list(s) Converts s to a list. s.append(x) Appends a new element, x, to the end of s. s.extend(t) Appends a new list, t, to the end of s. 6. SORT >>> student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ] >>> sorted(student_tuples, key=lambda student: student[2]) # sort by age [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] 7. ANY IMMUTABLE OBJECT AS A DICTIONARY KEY VALUE Dictionaries are the only built-in mapping type and are Python’s version of a hash table or associative array.You can use any immutable object as a dictionary key value (strings, numbers, tuples, and so on). Lists, dictionaries, and tuples containing mutable objects cannot be used as keys (the dictionary type requires key values to remain constant) CHAPTER 4 OPERATORS AND EXPRESSIONS 1. .. CHAPTER 5. PROGRAM STRUCTURE AND CONTROL FLOW 1. enumerate(s) >>> a [1, 4, 3] >>> for i,x in enumerate(a): ... print (i,x) ... (0, 1) (1, 4) (2, 3) >>> 2. Build-in exceptions Table 5.1 Built-in Exceptions Exception Description BaseException The root of all exceptions. GeneratorExit Raised by .close() method on a generator. KeyboardInterrupt Generated by the interrupt key (usually Ctrl+C). SystemExit Program exit/termination. Exception Base class for all non-exiting exceptions. StopIteration Raised to stop iteration. StandardError Base for all built-in exceptions (Python 2 only). In Python 3, all exceptions below are grouped under Exception. ArithmeticError Base for arithmetic exceptions. FloatingPointError Failure of a floating-point operation. ZeroDivisionError Division or modulus operation with 0. AssertionError Raised by the assert statement. AttributeError Raised when an attribute name is invalid. EnvironmentError Errors that occur externally to Python. IOError I/O or file-related error. OSError Operating system error. EOFError Raised when the end of the file is reached. ImportError Failure of the import statement. LookupError Indexing and key errors. IndexError Out-of-range sequence index. KeyError Nonexistent dictionary key. MemoryError Out of memory. NameError Failure to find a local or global name. UnboundLocalError Unbound local variable. ReferenceError Weak reference used after referent destroyed. RuntimeError A generic catchall error. NotImplementedError Unimplemented feature. SyntaxError Parsing error. IndentationError Indentation error. TabError Inconsistent tab usage (generated with -tt option). SystemError Nonfatal system error in the interpreter. TypeError Passing an inappropriate type to an operation. ValueError Invalid type. UnicodeError Unicode error. UnicodeDecodeError Unicode decoding error. UnicodeEncodeError Unicode encoding error. UnicodeTranslateError Unicode translation error. 3. DEFINE NEW EXCEPTIONS class DeviceError(Exception): def __init__(self,errno,msg): self.args = (errno, msg) self.errno = errno self.errmsg = msg # Raises an exception (multiple arguments) raise DeviceError(1, 'Not Responding') 4. CONTEXT MANAGERS AND THE "WITH" STATEMENT ('QUITE IMPORTANT') The with statement allows a series of statements to execute inside a runtime context that is controlled by an object that serves as a context manager. Here is an example: with open("debuglog","a") as f: f.write("Debugging\n") statements f.write("Done\n") import threading lock = threading.Lock() with lock: # Critical section statements # End critical section In the first example, the with statement automatically causes the opened file to be closed when control-flow leaves the block of statements that follows. In the second example, the with statement automatically acquires and releases a lock when control enters and leaves the block of statements that follows. CHAPTER 6 FUNCTIONS AND FUNCTIONAL PROGRAMMING 1. In addition, the use of mutable objects as default values may lead to unintended behavior: def foo(x, items=[]): items.append(x) return items foo(1) # returns [1] foo(2) # returns [1, 2] foo(3) # returns [1, 2, 3] Notice how the default argument retains modifications made from previous invocations. To prevent this, it is better to use None and add a check as follows: def foo(x, items=None): if items is None: items = [] items.append(x) return items 2. HOW TO USE **PARAMS def make_table(data, **parms): # Get configuration parameters from parms (a dict) fgcolor = parms.pop("fgcolor","black") bgcolor = parms.pop("bgcolor","white") width = parms.pop("width",None) ... # No more options if parms: raise TypeError("Unsupported configuration options %s" % list(parms)) make_table(items, fgcolor="black", bgcolor="white", border=1, borderstyle="grooved", cellpadding=10, width=400) 3. DECORATORS @trace def square(x): return x*x The preceding code is shorthand for the following: def square(x): return x*x square = trace(square) 4. Coroutines and yield Expressions >>> r = receiver() >>> r.next() # Advance to first yield (r._ _next_ _() in Python 3) Ready to receive >>> r.send(1) Got 1 >>> r.send(2) Got 2 >>> r.send("Hello") Got Hello >>> 5. List Comprehension a = [-3,5,2,-10,7,8] b = 'abc' c = [2*s for s in a] # c = [-6,10,4,-20,14,16] d = [s for s in a if s >= 0] # d = [5,2,7,8] e = [(x,y) for x in a # e = [(5,'a'),(5,'b'),(5,'c'), for y in b # (2,'a'),(2,'b'),(2,'c'), if x > 0 ] # (7,'a'),(7,'b'),(7,'c'), # (8,'a'),(8,'b'),(8,'c')] f = [(1,2), (3,4), (5,6)] g = [math.sqrt(x*x+y*y) # f = [2.23606, 5.0, 7.81024] for x,y in f] Notes: if using parentheses, we get GENERATOR EXPRESSIONS # Read a file f = open("data.txt") # Open a file lines = (t.strip() for t in f) # Read lines, strip # trailing/leading whitespace comments = (t for t in lines if t[0] == '#') # All comments for c in comments: print(c) In this example, the generator expression that extracts lines and strips whitespace does not actually read the entire file into memory.The same is true of the expression that extracts comments. Instead, the lines of the file are actually read when the program starts iterating in the for loop that follows. During this iteration, the lines of the file are produced upon demand and filtered accordingly. In fact, at no time will the entire file be loaded into memory during this process.Therefore, this would be a highly efficient way to extract comments from a gigabyte-sized Python source file. 6. RECURSION NOTICE Care should also be taken when mixing recursive functions and decorators. If a decorator is applied to a recursive function, all inner recursive calls now get routed through the decorated version. For example: @locked def factorial(n): if n <= 1: return 1 else: return n * factorial(n - 1) # Calls the wrapped version of factorial If the purpose of the decorator was related to some kind of system management such as synchronization or locking, recursion is something probably best avoided. CHAPTER 7. CLASSES AND OBJECT-ORIENTED PROGRAMMING 1. Multi-inheritance => Refer to a latter blog: Method Resolution Order Basically, the ordering is determined according to the C3 linearization algorithm . =>“A Monotonic Superclass Linearization for Dylan” (K. Barrett, et al, presented at OOPSLA’96)" Follows "most specialized" class to the "lease specialized" class and then the order in parenthesis. 2. STATIC METHODS VS CLASS METHODS A static method is an ordinary function that just happens to live in the namespace defined by a class. It does not operate on any kind of instance.To define a static method, use the @staticmethod decorator as shown here: class Foo(object): @staticmethod def add(x,y): return x + y 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. For example: class Times(object): factor = 1 @classmethod def mul(cls,x): return cls.factor*x class TwoTimes(Times): factor = 2 x = TwoTimes.mul(4) # Calls Times.mul(TwoTimes, 4) -> 8 3. Properties Properties 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 when accessed. Here is a simple example: class Foo(object): def __init__(self,name): self._ _name = name @property def name(self): return self.__name @name.setter def name(self,value): if not isinstance(value,str): raise TypeError("Must be a string!") self.__name = value @name.deleter def name(self): raise TypeError("Can't delete name") f = Foo("Guido") n = f.name # calls f.name() - get function f.name = "Monty" # calls setter name(f,"Monty") f.name = 45 # calls setter name(f,45) -> TypeError del f.name # Calls deleter name(f) -> TypeError 4. Data Encapsulation and Private Attribute To fix this problem, all names in a class that start with a double underscore, such as __Foo, are automatically mangled to form a new name of the form _Classname__Foo. This effectively provides a way for a class to have private attributes and methods because private names used in a derived class won’t collide with the same private names used in a base class. Here’s an example: class A(object): def __init__(self): self.__X = 3 # Mangled to self._A__X def __spam(self): # Mangled to _A__spam() pass def bar(self): self.__spam() # Only calls A.__spam() class B(A): def __init__(self): A.__init__(self) self.__X = 37 # Mangled to self._B__X def __spam(self): # Mangled to _B__spam() pass 5.
说明 · · · · · ·
表示其中内容是对原文的摘抄