What are the advanced special effects of Python? What's the use of it? The most complete tutorial in history!

Source: Internet
Author: User

This article highlights the following:

Some of the high-level uses of the Python language include the following features:

    • Generators Generator usage
    • Common usage of collections package
    • Common usage of Itertools package
    • Packing/unpacking Package/Unpacking characteristics
    • Decorators Decorator
    • Context Managers contextual management period

Output results

01123581321345589144233377610987

In Python, you can use a builder expression to iterate over an object, and the biggest difference between a generator expression and a list is whether the result is computed once, for example, as follows:

The collections package is a module of the standard library, the main purpose of which is to extend the container-related data types,

We use DIR to see which modules are in the collections package:

>>> import collections>>> dir(collections)[‘Callable‘, ‘Container‘, ‘Counter‘, ‘Hashable‘, ‘ItemsView‘, ‘Iterable‘, ‘Iterator‘, ‘KeysView‘, ‘Mapping‘, ‘MappingView‘, ‘MutableMapping‘, ‘MutableSequence‘, ‘MutableSet‘, ‘OrderedDict‘, ‘Sequence‘, ‘Set‘, ‘Sized‘, ‘ValuesView‘, ‘__all__‘, ‘__builtins__‘, ‘__doc__‘, ‘__file__‘, ‘__name__‘, ‘__package__‘, ‘_abcoll‘, ‘_chain‘, ‘_class_template‘, ‘_eq‘, ‘_field_template‘, ‘_get_ident‘, ‘_heapq‘, ‘_imap‘, ‘_iskeyword‘, ‘_itemgetter‘, ‘_repeat‘, ‘_repr_template‘, ‘_starmap‘, ‘_sys‘, ‘defaultdict‘, ‘deque‘, ‘namedtuple‘]

We take counter as an example:

from collections import Countera = Counter(‘blue‘)b = Counter(‘yellow‘)print(a)print(b)print((a + b).most_common(3))

The output results are as follows:

Counter({‘u‘: 1, ‘e‘: 1, ‘l‘: 1, ‘b‘: 1})Counter({‘l‘: 2, ‘y‘: 1, ‘e‘: 1, ‘o‘: 1, ‘w‘: 1})[(‘l‘, 3), (‘e‘, 2), (‘y‘, 1)]

In addition Defaultdict is also a module that I often use, defaultdict is a subclass of Dict, allowing us to dynamically create non-existent properties through factory methods, such as the following:

from collections import defaultdictmy_dict = defaultdict(lambda: ‘Default Value‘)my_dict[‘a‘] = 42print(my_dict[‘a‘])print(my_dict[‘b‘])

The results of the operation are as follows:

42Default Value

In my work I often use defaultdict to construct a tree-shaped data structure to meet my regular needs, examples are as follows:

from collections import defaultdictimport jsondef tree(): """ Factory that creates a defaultdict that also uses this factory """ return defaultdict(tree)root = tree()root[‘Page‘][‘Python‘][‘defaultdict‘][‘Title‘] = ‘Using defaultdict‘root[‘Page‘][‘Python‘][‘defaultdict‘][‘Subtitle‘] = ‘Create a tree‘root[‘Page‘][‘Java‘] = Noneprint(json.dumps(root, indent=4))

The results of the operation are as follows:

{ "Page": { "Python": { "defaultdict": { "Subtitle": "Create a tree", "Title": "Using defaultdict" } }, "Java": null }}

Output Result:

(1, 2)(1, 3)(1, 4)(2, 3)(2, 4)(3, 4)

Another chain module is also one of the common modules

Chain Use Example:

from itertools import chainfor c in chain(range(3), range(12, 15)): print(c)

The output results are as follows:

012121314

In addition, there are a lot of common usage in Itertools Toolkit, there are no more one by one examples, you can try it yourself.

Packing/unpacking characteristics

The results of the operation are as follows:

Call function repeat using a list of arguments:catscatscatscatsCall function repeat using a dictionary of keyword arguments:catscatscatscats

Finally, we return to the example of the function parameter:

def f(*args, **kwargs): print("Arguments: ", args) print("Keyword arguments: ", kwargs)f(3, 4, 9, foo=42, bar=7)

The above code output:

Arguments: (3, 4, 9)Keyword arguments: {‘bar‘: 7, ‘foo‘: 42}

Decorators Decorator

Decorator This syntax sugar believe that the use of flask or bottle students should not be unfamiliar, using Django should often encounter, but have you ever thought of this syntax sugar application scenario? I made a simple arrangement, with the following decorations:

    • Cache Adorner
    • Permission Validation Adorner
    • Timing Decorators
    • Log Decorator
    • Route Adorner
    • Exception handling Adorner
    • Error retry Adorner

Let's take a cache decorator example:

def cache(function): cached_values = {} # Contains already computed values def wrapping_function(*args): if args not in cached_values: # Call the function only if we haven‘t already done it for those parameters cached_values[args] = function(*args) return cached_values[args] return wrapping_function@cachedef fibonacci(n): print(‘calling fibonacci(%d)‘ % n) if n < 2: return n return fibonacci(n-1) + fibonacci(n-2)print([fibonacci(n) for n in range(1, 9)])

The above code output:

calling fibonacci(1)calling fibonacci(2)calling fibonacci(0)calling fibonacci(3)calling fibonacci(4)calling fibonacci(5)calling fibonacci(6)calling fibonacci(7)calling fibonacci(8)[1, 1, 2, 3, 5, 8, 13, 21]

In Python3, there is a package called LRUCache, which is implemented using the syntax sugar of the adorner.

The simple and practical LRUCache are as follows:

from functools import lru_cache@lru_cache(maxsize=None)def fibonacci(n): print(‘calling fibonacci(%d)‘ % n) if n < 2: return n return fibonacci(n-1) + fibonacci(n-2)print([fibonacci(n) for n in range(1, 9)])

Operation Result:

calling fibonacci(1)calling fibonacci(2)calling fibonacci(0)calling fibonacci(3)calling fibonacci(4)calling fibonacci(5)calling fibonacci(6)calling fibonacci(7)calling fibonacci(8)[1, 1, 2, 3, 5, 8, 13, 21]

Context Managers contextual management period

Finally, we look at the context manager in Python, this syntax sugar in the resource management has a very common use of the scene, such as I used with the open ("file") as the use of using with the after do not worry about the file will not be closed, in the processing of socket programming can also be used. This syntactic sugar is actually not difficult is the realization of two magic methods, enter and exit, a control entrance, a control exit.

General use with to count an example of a code run time:

from time import timeclass Timer(): def __init__(self, message): self.message = message def __enter__(self): self.start = time() return None # could return anything, to be used like this: with Timer("Message") as value: def __exit__(self, type, value, traceback): elapsed_time = (time() - self.start) * 1000 print(self.message.format(elapsed_time))with Timer("Elapsed time to compute some prime numbers: {}ms"): primes = [] for x in range(2, 500): if not any(x % p == 0 for p in primes): primes.append(x) print("Primes: {}".format(primes))

Output Result:

Primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499]Elapsed time to compute some prime numbers: 1.055002212524414ms

Summarize

In fact, Python is a special human language, any of the problems often encountered in the project, the more difficult to deal with the model has a corresponding more elegant solution. Some Java classmates write Python code often look like writing C, there is no Python language shadow, so simple to sort out the next step of Python usage, I hope to help some students.

Welcome to my Blog or public number: Https://home.cnblogs.com/u/Python1234/Python Learning Communication

Welcome to my thousand People Exchange Learning Group: 125240963

What are the advanced special effects of Python? What's the use of it? The most complete tutorial in history!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.