17 Python tricks

Source: Internet
Author: User
When a third-party package of python is released, a limited interface is displayed to the outside. you do not want all functions or classes in the code to be imported externally __. in py, add the _ all _ attribute. in this list, enter the class or function name that can be imported, which can be used to restrict the import and prevent external import of other functions or classes. #! Usrbinenvpython #-*-coding: UTF-8-*-frombaseimportapba .. display limited interfaces to external

When the python third-party package is released, you do not want all functions or classes in the code to be imported externally. in py, add the all attribute. in this list, enter the class or function name that can be imported, which can be used to restrict the import and prevent external import from other functions or classes.

#!/usr/bin/env python# -*- coding: utf-8 -*-from base import APIBasefrom client import Clientfrom decorator import interface, export, streamfrom server import Serverfrom storage import Storagefrom util import (LogFormatter, disable_logging_to_stderr,                       enable_logging_to_kids, info)all = ['APIBase', 'Client', 'LogFormatter', 'Server',           'Storage', 'disable_logging_to_stderr', 'enable_logging_to_kids',           'export', 'info', 'interface', 'stream']
With Magic

The with statement must be supported.Objects of the context management protocol,The context management protocol includes two methods: enter and exit. The context of the with statement must be executed using these two methods.Enter and exitOperation.

WhereContext expressionIs the expression following with, which returns a Context Management object.

# Common use cases with open ("test.txt", "r") as my_file: # note that the return value of the enter () method is assigned to my_file, for line in my_file: print line

For details, refer to this article to discuss the with statement of Python.

Knowing the specific principles, we can customize the classes that support the context management protocol, and implement the enter and exit methods in the class.

#! /Usr/bin/env python #-*-coding: UTF-8-*-class MyWith (object): def init (self): print "init method" def enter (self ): print "enter method" return self # def exit (self, exc_type, exc_value, exc_traceback): print "exit method" if exc_traceback is None: print "Exited without Exception" return True else: print "Exited with Exception" return Falsedef test_with (): with MyWith () as my_with: print "running my_with" print "------ split line -----" with MyWith () as my_with: print "running before Exception" raise Exception print "running after Exception" if name = 'main ': test_with ()

The execution result is as follows:

Init methodenter methodrunning my_withexit methodExited without Exception ------ split line ----- init methodenter methodrunning before Exceptionexit methodExited with ExceptionTraceback (most recent call last): File "bin/python", line 34, in
 
  
Exec (compile (filef. read (), file, "exec") File "test_with.py", line 33, in
  
   
Test_with () File "test_with.py", line 28, in test_with raise ExceptionException
  
 

It is proved that the enter method will be executed first, then the logic in with will be called, and then exit will be executed for exit processing. In addition, the exit can be normal even if an exception occurs.

Filter usage

Compared with filters, map and reduce are used more frequently. filters are called according to certain rules.FilterDrop some elements.

#! /Usr/bin/env python #-*-coding: UTF-8-*-lst = [1, 2, 3, 4, 5, 6] # True is returned for all odd numbers, even numbers return False and print filter is filtered out (lambda x: x % 2! = 0, lst) # output result [1, 3, 5]
One row for judgment

If the condition is met, the return value is the variable after the equal sign. Otherwise, the return value is the else statement.

Lst = [1, 2, 3] new_lst = lst [0] if lst is not None else Noneprint new_lst # Print result 1
Decorator Singleton

Simple Singleton mode with decorator

# Singleton (cls): instances = dict () # def _ singleton (* args, ** kwargs): if cls not in instances: # If it does not exist, create and put the Dictionary instances [cls] = cls (* args, ** kwargs) return instances [cls] return _ singleton @ singletonclass Test (object ): passif name = 'main': t1 = Test () t2 = Test () # The two have the same address: print t1, t2
Staticmethod decorator

There are two common decorations in the class:

  • Common member functions, where the first implicit parameter isObject

  • Classmethod modifier, Class method (it is very similar to the class method in OC), where the first implicit parameter isClass

  • Staticmethod decorator, Without any implicit parameters.The static method in python is similar to the static method in C ++.

#! /Usr/bin/env python #-*-coding: UTF-8-*-class A (object): # normal member function def foo (self, x ): print "executing foo (% s, % s)" % (self, x) @ classmethod # use classmethod to decorate def class_foo (cls, x ): print "executing class_foo (% s, % s)" % (cls, x) @ staticmethod # decorate def static_foo (x) using staticmethod: print "executing static_foo (% s) "% xdef test_three_method (): obj = A () # directly call the member method obj. foo ("para") # Here, the obj object is an implicit parameter of the member function, that is, self obj. class_foo ("para") # The class is passed in as an implicit parameter, that is, cls. class_foo ("para") # Call obj using a more direct class method. static_foo ("para") # The static method does not have any implicit parameters, but. static_foo ("para") if name = 'main': test_three_method () # function output executing foo (
 
  
, Para) executing class_foo (
  
   
, Para) executing class_foo (
   
    
, Para) executing static_foo (para)
   
  
 
Property modifier
  • Define private class attributes

Property and decorator are combined to realize property privatization (Simpler and safer get and set methods).

# Python built-in function property (fget = None, fset = None, fdel = None, doc = None)

Fget is a function to get the attribute value, fset is a function to set the attribute value, fdel is a function to delete the attribute, and doc is a string (like a comment ). From the implementation perspective, these parameters are optional.

Property has three methods: getter (), setter (), and delete () to specify fget, fset, and fdel. This indicates the following line:

Class Student (object): @ property # equivalent to property. getter (score) or property (score) def score (self): return self. _ score @ score. setter # is equivalent to score = property. setter (score) def score (self, value): if not isinstance (value, int): raise ValueError ('score must be an integer! ') If value <0 or value> 100: raise ValueError ('score must between 0 ~ 100! ') Self. _ score = value
Iter magic
  • Through the combination of yield and iter, we can convert an object into an iterative one.

  • Through str rewriting, you can print objects directly in the desired form

#!/usr/bin/env python# -*- coding: utf-8 -*-class TestIter(object):    def init(self):        self.lst = [1, 2, 3, 4, 5]    def read(self):        for ele in xrange(len(self.lst)):            yield ele    def iter(self):        return self.read()    def str(self):        return ','.join(map(str, self.lst))    repr = strdef test_iter():    obj = TestIter()    for num in obj:        print num    print objif name == 'main':    test_iter()
Magic partial

Partial is similar to a function (function object) in C ++ ).

Stackoverflow provides a running method similar to partial:

def partial(func, *part_args):    def wrapper(*extra_args):        args = list(part_args)        args.extend(extra_args)        return func(*args)    return wrapper

Use the closure feature to bind some function parameters in advance and return an callable variable until the actual call is executed:

#! /Usr/bin/env python #-*-coding: UTF-8-*-from functools import partialdef sum (a, B): return a + bdef test_partial (): fun = partial (sum, 2) # bind a parameter beforehand. fun becomes a variable that only needs one parameter. the variable print fun (3) # sum (2, 3) if name = 'main': test_partial () # execution result 5
Mysterious eval

I understand eval as an embedded python interpreter (this interpretation may be biased). it will interpret the string as the corresponding code and execute it, and return the execution result.

Let's take a look at the following example:

#! /Usr/bin/env python #-*-coding: UTF-8-*-def test_first (): return 3def test_second (num ): return numaction = {# it can be viewed as a sandbox "para": 5, "test_first": test_first, "test_second": test_second} def test_eavl (): condition = "para = 5 and test_second (test_first)> 5" res = eval (condition, action) # explain condition and execute print resif name = '_ according to the action corresponding to the action '_
Exec
  • Exec ignores the return value in Python and always returns None. eval returns the return value of the executed code or statement.

  • When executing code, exec and eval perform the same behavior except the return value.

  • Compile (source ,' ', Mode) compile the bytecode. The value of mode is exec and eval.

#! /Usr/bin/env python #-*-coding: UTF-8-*-def test_first (): print "hello" def test_second (): test_first () print "second" def test_third (): print "third" action = {"test_second": test_second, "test_third": test_third} def test_exec (): exec "test_second" in actionif name = 'main': test_exec () # The execution result cannot be viewed.
Getattr

Getattr (object, name [, default]) returns the object's naming attributes. the attribute name must be a string. If the string is one of the object's property names, the result is the value of this property. For example, getattr (x, 'foobar') is equivalent to x. foobar. If the attribute name does not exist, the default value is returned if the default value exists. otherwise, AttributeError is triggered.

# Example class TestGetAttr (object): test = "test attribute" def say (self): print "test method" def test_getattr (): my_test = TestGetAttr () try: print getattr (my_test, "test") failed t AttributeError: print "Attribute Error! "Try: getattr (my_test," say ") () T t AttributeError: # print" Method Error! "If name = 'main': test_getattr () # output result test attributetest method
Command line processing
def process_command_line(argv):    """    Return a 2-tuple: (settings object, args list).    `argv` is a list of arguments, or `None` for ``sys.argv[1:]``.    """    if argv is None:        argv = sys.argv[1:]    # initialize the parser object:    parser = optparse.OptionParser(        formatter=optparse.TitledHelpFormatter(width=78),        add_help_option=None)    # define options here:    parser.add_option(      # customized description; put --help last        '-h', '--help', action='help',        help='Show this help message and exit.')    settings, args = parser.parse_args(argv)    # check number of arguments, verify values, etc.:    if args:        parser.error('program takes no command-line arguments; '                     '"%s" ignored.' % (args,))    # further process settings & args if necessary    return settings, argsdef main(argv=None):    settings, args = process_command_line(argv)    # application code here, like:    # run(settings, args)    return 0        # successif name == 'main':    status = main()    sys.exit(status)
Read/write csv files
# Reading a file from a csv file is similar to reading a traditional File: import csvwith open('data.csv ', 'RB') as f: reader = csv. reader (f) for row in reader: print row # write import csvwith open ('data.csv ', 'WB') as f: writer = csv to a csv file. writer (f) writer. writerow (['name', 'address', 'age']) # write data in a single row = [('xiaoming', 'China', '10 '), ('Lily', 'USA', '12')] writer. writerows (data) # write multiple rows
Time format conversion

Just send a picture on the Internet and check the document. this is hard to remember.

String formatting

A very useful feature that many people do not know:

>>> name = "andrew">>> "my name is {name}".format(name=name)'my name is andrew'

The above are the details shared by 17 Python geeks. For more information, see other related articles in the first PHP community!

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.