Python variable parameters and standard output relocation

Source: Internet
Author: User
Tags flush stdin in python

When you print with the Python built-in function, you will find that it supports any number of arguments, that is, the call parameters for print are not fixed. For example:

print "Hello"
Print "I am", name
Print "Now", Time, "What are you doing?", Name, "!"

This benefits from Python's "variable parameters", in Python, where you can use * and * * To set variable parameters, which are the difference between * passing a parameter tuple, * * Passing a parameter dictionary, which can be mixed simultaneously. Use caution when mixing, because their order is important in Python. Parameters are grouped into 4 categories, not all categories are required. They have to be defined in the order in which they are not needed to skip.
1 the necessary parameters
2 Optional parameters
3) Excessive position parameters
4 Too much keyword parameter

Def funname (A, B=none, *c, **d):

This order is necessary because *args and **kwargs only accept any other parameters that are not put in. Without this order, when you call a function with positional arguments, Python does not know which value is being declared and what is being treated as an excess parameter.
Also note that when a function can accept many of the necessary parameters and optional parameters, it simply defines an excess parameter type. Look at the following example:

The code is as follows Copy Code

def add (A, B, c):
Return a + B + C
>>> Add (1, 2, 3)
6
>>> Add (a=4, b=5, c=6)
15
>>> args = (2, 3)
>>> Add (1, *args)
6
>>> kwargs={' B ': 8, ' C ': 9}
>>> Add (a=7, **kwargs)
24
>>> Add (a=7, *args)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Typeerror:add () got multiple values for keyword argument ' a '
>>> Add (1, 2, a=7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Typeerror:add () got multiple values for keyword argument ' a '

Note the last few lines of this example, paying special attention to whether you want to explicitly pass keyword parameters when passing a tuple as a variable parameter. Because Python uses order rules to extend an excessive number of arguments, the position parameter is placed in front of it. In this example, the last two calls are the same, and Python cannot determine which value is given to a.

Here's an example to simulate the implementation of print:

The code is as follows Copy Code

    >>> Import sys
    >>> def myprint (*argv):
         sys.stdout.write ("". Join ([STR (i) for I in argv]) + "n")
    >>& Gt Print "I Believe", "is the ' End of". The
    I believe is the "end of" the world.
    >>> myprint ("I Believe", "the" is the "the") The
    I believe is the "end of" the world.
    >>> print "Tuple:", (1, 2, 3), "list:", [1, 2, 3], "dict:", {"Begin": -2012, "End": 2012}     Tuple: (1, 2, 3) List: [1, 2, 3] dict: {' Begin ': -2012, ' End ':}
    >> > Myprint ("Tuple:", (1, 2, 3), "list:", [1, 2, 3], "dict:", {"Begin": -2012, "End": "}"
    tuple: (1, 2, 3) List: [1, 2, 3] dict: {' Begin ': -2012, ' End ':}

Print defaults to output to stdout, and in the case of a terminal-run program, print output to the console without redirection. If you want to do code to write the output of print to log file, you can modify the stdout file object to implement. Similarly, relocating standard input and standard error output modifies stdin and stderr file objects respectively.
The following example captures the output of all print, adding a time display to each row of the output:

The code is as follows Copy Code

Import sys, TIME
Class Myoutput ():
def __init__ (self, FD):
Self.formattime ()
Self.out = FD
Self.newline = True
def formattime (self):
Return Time.strftime ("%h:%m:%s", Time.localtime ())
Def write (self, s):
If Self.newline:
Self.out.write (Self.formattime ())
Self.newline = False
Self.out.write (s)
If S.endswith ("n"):
Self.newline = True
def flush (self):
Self.out.flush ()
Sys.stdout = Myoutput (sys.stdout)
Print "program begin."
MyList = [5, 4, 3, 2, 1]
Print "prev:", mylist
Mylist.sort ()
Print "After:", mylist
Time.sleep (3)
Print "program end."

Related Article

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.