Annotation: English title of this article is 'Advanced Design Patterns in Python', can be literally translated as 'Python in the advanced design mode.' But I read through the full text of the article after the discovery of content with our usual understanding of design patterns is very different, original post comments there are also other readers of this. Thus, according to the content of my article will be translated title 'Python advanced programming skills,' In case of disagreement, please leave a message Air Jordan Outlet pointed out, very grateful. Body: This article shows you some advanced Python design structure and methods of their use. In their daily work, you can choose according to need the appropriate data structure, for example, to quickly find the requirements for data consistency requirements or requirements of the index, but can also be combined with various data structures fit together , thereby generating logical data model and easy to understand. Python data structures from the syntactic point of view is very intuitive, and offers a number of optional. This guide attempts to most commonly Nike Air Max 2015 Women used data structures knowledge put together, and discuss its offer optimum usage. Derivation of formula (Comprehensions) If you've used for a long time Python, then you should at least have heard of list comprehensions (list comprehensions). This is a for loop, if a method of expression and assignment statements into a single statement. In other words, you can make a list of mapping or filtering operation by an expression. A list of derivation contains the following sections: an input sequence represents a member of the variable input sequence an optional assertion expression a member of the input sequence that satisfies the assertion expression is converted into an output member of the list output expression example We need all the input is greater than 0 in a list from the integer square generate a new sequence, so you might write: num = [1, 4, -5, 10, -7, 2, 3, -1] filtered_and_squared = [] for number in num: if number \u0026 gt; 0: filtered_and_squared.append (number ** 2) print filtered_and_squared # [1, 16, 100, 4, 9] is very simple is not it? But this will have four lines of code, plus two nested append a completely unnecessary operation. And if you use filter, lambda and map function, it is possible to greatly simplify the code: num = [1, 4, -5, 10, -7, 2, 3, -1] filtered_and_squared = map (lambda x: x ** 2 , filter (lambda x: x \u0026 gt; 0, num)) print filtered_and_squared # [1, 16, 100, 4, 9] ah that way the code will expand in the horizontal direction. So whether or not to continue to simplify the code? List comprehensions can give us the answer: num = [1, 4, -5, 10, -7, 2, 3, -1] filtered_and_squared = [x ** 2 for x in num if x \u0026 gt; 0] print filtered_and_squared # [ 1, 16, 100, 4, 9] iterators (iterator) traversing the input of each member of the Mens Nike Free 3.0 Wool Skin Shoes Blue Yellow sequence num x assertion formula determines whether each member if the member is greater than greater than zero after zero, were handed over to the output of expression, the square becomes an output list of members. List comprehensions are encapsulated in a list, so obviously it can immediately generate a new list. There is only one type of a function call does not implicitly called lambda functions, list comprehensions is the use of a conventional iterator, an expression and a controlled expression if optional parameters. On the other hand, the list is derived also may be some negative effects, that is, the entire list must be disposable loading in memory, and which examples above is not a problem, even after several times to expand also is not a problem. But always to the limit, the memory will always be exhausted. For the above problems, the generator (Generator) can be a good solution. Generator expressions are not the entire list at once loaded into memory, but generates a generator object (Generator objector), so only once to load a list element. Generator expressions with list comprehensions has almost the same grammatical structure, except that the generator expressions are surrounded by parentheses instead of square brackets: num = [1, 4, -5, 10, -7, 2, 3 , -1] filtered_and_squared = (x ** 2 for x in num if x \u0026 gt; 0) print filtered_and_squared # \u0026 lt; generator object \u0026 lt; genexpr \u0026 gt; at 0x00583E18 \u0026 gt; for item in filtered_and_squared: print item # 1, 16, 100 4, 9 This is slightly higher than the efficiency of a list comprehension, let us once again transform the code: num = [1, 4, -5, 10, -7, 2, 3, -1] def square_generator (optional_parameter): return (x * * 2 for x in num if x \u0026 gt; optional_parameter) print square_generator (0) # \u0026 lt; generator object \u0026 lt; genexpr \u0026 gt; at 0x004E6418 \u0026 gt; # Option Ifor k in square_generator (0): print k # 1, 16, 100, 4, 9 # Option IIg = list (square_generator (0)) print g # [1, 16, 100, 4, 9] unless Mens Nike Free Run 3 Shoes Black Red 3 special Air Max 2011 Womens Blue Black reasons, should always use a generator expression in your code. But unless it is the face of a very large list, otherwise it will not see the obvious difference. The following example uses zip () function once the processing of two or more elements in the list: alist = ['a1', 'a2', 'a3'] blist = ['1', '2', '3'] for a, b in zip (alist, blist): print a, b # a1 1 # a2 2 # a3 3 and then look at a by two-stage list comprehensions directory traversal example: import osdef tree (top): for path, names, fnames in os.walk (top): Air Max 2011 Navy Blue Black for fname in fnames: yield os.path.join (path, fname) for name in tree ('C: \\ Users \\ XXX \\ Downloads \\ Test'): print name decorators (Decorators) Decorators provides us with an effective way to increase the existing function or class functions. Sound is not like Java, Aspect Oriented Programming (Aspect-Oriented Programming) concept? Both are simple, and the decorator has a more powerful features. For example, suppose you want at the entry and exit points of a function to do some special operations (such as some security, tracking and locking and other operations) can use the decorator. Decoration is a package of special function to another function: the main function is called, and its return value will be passed to the decorator, the next decoration will return a package of alternative function the main function, the other part of the program to see to this wrapper function will be. def timethis (func): '' 'Decorator that reports the execution time.' '' pass @ timethisdef countdown (n): while n \u0026 gt; 0: n - = 1 syntactic sugar @ identifies the decorator. Well, let us return to the earlier example. We will do some of the more typical use decorator operations: import timefrom functools import wrapsdef timethis (func): '' 'Decorator that reports the execution time.' ''wraps (Func) def wrapper (* args, ** Mens Nike Free 3.0 V2 Shoes White Black Red kwargs) : start = time.time () result = func (* args, ** kwargs) end = Nike Air Max 95 Men time.time () print (func .__ name__, end-start) return result return wrapper @ timethisdef countdown (n): while n \u0026 gt ; 0: n - = 1countdown (100000) # ('countdown', 0.006999969482421875) when you write the following code:timethisdef countdown (n): means that you separate performed the following steps: def countdown (n): .. .countdown = timethis (countdown) decorator function code creates a new function (positive in this example the wrapper function), it uses * args and ** kwargs receiving any input parameters, and call the original in this function function and returns the result. You can put any additional code (for example, in this case the timing operations) according to their needs, wrapper newly created as a result of back and replace the original function. decoratordef function (): print (\u0026 quot; inside function \u0026 quot;) When the compiler to view the above Mens Nike Free 3.0 V2 Shoes White Black Red code, function () function will be compiled, and the function returns the object code that will be passed to the decorator, the decorator will do After-related operations with a new function object instead of the original function. Decorative code is what? Most of the examples are defined as a function of the decorator, but I found the decoration is defined as a class easier to understand its function, and so it can bring the power of the decorator mechanism. Realization of a decorator's class the only requirement is that it must be able to function as the general use, which means it must be invoked. So, if you want to do in this class must implement __call__ methods. Such a decorator should be used to do what? It can do anything, but usually it is used when you want to use the original function in some special place, but not required, for example: class decorator (object): def __init __ (self, f): print (\u0026 quot; inside decorator .__ init __ () \u0026 quot;) f () # Prove that function definition has completed def __call __ (self): print (\u0026 quot; inside decorator .__ call __ () \u0026 quot;) @ decoratordef function (): print (\u0026 quot; inside function () \u0026 quot;) print (\u0026 quot; Finished decorating function () \u0026 quot;) function () # inside decorator .__ Mens Nike Free Run 3 Shoes Black Red 3 init __ () # inside function () # Finished decorating function () # inside decorator .__ call __ () Translator's Note: 1 Syntax sugardecorator equivalent function = decorator (function), the decorator of this call __init__ print 'inside decorator .__ init __ ()' 2. Then execute f () print 'inside function ()' 3. Then perform ' print ('Finished decorating function ()') '4. Finally, when calling function function, due to the use of packaging decorators, so execution of __call__ decorator print' inside decorator .__ call __ () '. A more practical example: def decorator (func): def modify (* args, ** kwargs): variable = kwargs.pop ('variable', None) print variable x, y = func (* args, ** kwargs) return x, y return modify @ decoratordef func (a, b): print a ** 2, b ** 2 return a ** 2, b ** 2func (a = 4, b = 5, variable = \u0026 quot; hi \u0026 quot; ) func (a = 4, b = 5) # hi # 16 25 # None # 16 25 context management library (ContextLib) contextlib module contains a context manager and with declarations related tools. Normally if you want to write Air Max 2011 Womens Grey Green Black a context manager, then you need to define a class that contains __enter__ methods and __exit__ methods, such as: import timeclass demo: def __init __ (self, label): self.label = label def __enter __ (self ): self.start = time.time () def __exit __ (self, exc_ty, exc_val, exc_tb): end = time.time () print ('{}: {}'. format (self.label, end - self. start)) complete example in this: import timeclass demo: def __init __ (self, label): self.label = label def __enter __ (self): self.start = time.time () def __exit __ (self, exc_ty, exc_val, exc_tb): end = time.time (.) print ('{}: {}' format (self.label, end - self.start)) with demo ('counting'): n = 10000000 while n \u0026 gt; 0: n - = 1 # counting: 1.36000013351 Nike Air Max context manager is activated with the declaration, the API involves two methods. 1. __enter__ method, when executed stream enters with a code block, __ enter__ method performs. And it will return an object for the context of use. 2. When the execution flow leaves with the code block, __ exit__ method is called, it will clean up resources to be used. Usecontextmanager decorators rewrite the example above: from contextlib import contextmanagerimport time @ contextmanagerdef demo (label): start = time.time () try: yield finally: end = time.time () print ('{}: {}' .format (label, end - start)) with demo ('counting'): n = 10000000 while n \u0026 gt; 0: n - = 1 # counting: 1.32399988174 look at the example above, all of the code before the function is similar yield Context Manager __enter__ content approach. And after all the code yield are as content __exit__ methods. If an exception occurs during the execution, it will trigger the yield Nike Free Run Womens statement. Descriptor (Descriptors) determines the object attributes describe how it is accessed. Describe the role of the custom action to take when you want to refer to a property that occurs. Constructed descriptor is to define at least one of the following three methods. Note that in the following instance that contains the object instance is accessed attributes, and owner are described by the class rhetoric. __get __ (self, instance, owner) - Get This method is called when when the property is via (value = obj.attr) way, the return value of this method will be part of this request code assigned to the property value. __set __ (self, instance, value) - this method is that when you want to set the value of the property (obj.attr = 'value') is called, this method does not return any value. __delete __ (self, instance) - When you delete a property from an object when (del obj.attr), calling this method. Translator's Note: For instance and owner of understanding, consider the following code: class Celsius (object): def __init __ (self, value = 0.0): self.value = float (value) def __get __ (self, instance, owner): return self.value def __set __ (self, instance, value): self.value = float (value) class Temperature (object): celsius = Celsius () temp = Temperature () temp.celsius #calls Celsius .__ get__ the above example, instance refers to a temp, and owner is Temperature. LazyLoading Properties example: import weakrefclass lazyattribute (object): def __init __ (self, f): self.data = weakref.WeakKeyDictionary () self.f = f def __get __ (self, obj, cls): if obj not in self.data : self.data [obj] = self.f (obj) return self.data [obj] class Foo (object):lazyattribute def bar (self): print \u0026 quot; Being lazy \u0026 quot; return 42f = Foo () print f. bar # Being lazy # 42print f.bar # 42 description is a good summary of the Python bindings methods (bound method) this concept, the binding method is Classic (classic classes) of achieving the core. In Classic, when a property is not found in the dictionary of an object instance, we will continue to the class dictionary lookup, and then to the base class dictionary, have been so down recursive lookup. If you find this property in a class dictionary, the object interpreter checks find is not a Python function object. If so, the return is not the object itself, but returns a curried (currying function) wrapper object. When calling the wrapper, it will first insert an instance before the parameter list, and then call the original function. Translator's Note: 1. currying - http://zh.wikipedia.org/wiki/%E6%9F%AF%E9%87%8C%E5%8C%962 function, method, bound method and unbound method distinction. First, the function (function) is created by the def or lambda. When a function is defined by the type or class statement to create Nike Free TR Fit a block, it will turn into a non-binding method (unbound method), and when (instance) to access this method through a class instance, it will turn into binding method (bound method), the binding method will automatically instance as the first argument passed to the method. In summary, the method is a function in the class appear, binding method is a method of binding a specific example, otherwise a non-binding approach. In summary, the descriptor is assigned to the class, and these special methods on when property is accessed automatically invoked according to the specific type of access. Yuan class (MetaClasses) Element class provides an effective way to change behavior Python class. Yuan class is defined as 'a kind of class.' Any instance is its own class are metaclasses. class demo (object): passobj = demo () print 2015 Nike Free 5.0 \u0026 quot; Class of obj is {0} \u0026 quot; .format (obj .__ class __) print \u0026 quot; Class of obj is {0} \u0026 quot; .format (demo .__ class __) # Class of obj is \u0026 lt; class '. __main __ demo' \u0026 gt; # Class of obj is \u0026 lt; type 'type' \u0026 gt; In the above example, we define a class demo, and generates an object obj a class. First, you can see the __class__ obj is demo. Interestingly it came, so the demo class, what is it? You can see a demo of __class__ type. So python class is a class type, in other words, in the example above is a demo of the object obj, and demo itself is an object of type. So that is one yuan class type, and is the most common element in python class, because it allows all classes python default metaclass. Because the meta class is a class, it is used to create class (as class is used to create objects like). However, do we not create a class through a standard class definition it? Yes it is, but the python inside the operating mechanism is as follows: when you see a class definition, python will collect all the properties to a dictionary. When the end of the class definition, python will decide metaclass class, we call it Meta bar. Finally, python implementation of Meta (name, bases, dct), where:. A Meta is a meta-class, so the call is an example of it. b. name is the class name of the new class. c. bases is a new base class tuple d. dct attribute names to objects, lists all the class attributes. So how do you define a class (A) metaclass it? In simple terms, itself or base class (Base_A) if one of a class (A) has __metaclass__ property exists, then this class (A / Base_A) is the class (A) of the metaclass. Otherwise, it will be a class type (A) of the metaclass. Mode (Patterns) 'easier to ask for forgiveness (EFAP) than to ask for permission,' the Python design principle is to say, 'easier to ask for forgiveness (EFAP) than ask for permission.' Do not advocate thoughtful design ideas, this principle is that it should try to try, if you encounter an error, then give proper treatment. Python has a powerful exception handling mechanism can support such an attempt, these mechanisms help programmers develop a more stable, more fault-tolerant programs. Singleton Singleton refers only exist while an instance of an object. Python provides many ways to achieve a single case. Null Null object can be used instead of the object type to avoid None None testing. Observer observer mode allows multiple objects to access the same data. Parameter Constructor Constructor is often assigned to the instance variable. This model can replace multiple manual assignment with one line of code. Summary Thanks for reading, if in doubt, please leave a message discussion.Python advanced programming skills