Concise python3 tutorial 17. More

Source: Internet
Author: User

Introduction

So far, we have learned most of the common knowledge in Python. In this chapter, we will have more knowledge to better understand python.

 

Transfer tuples

Do you want to return two different values from the function? To do this, use the tuples.

>>> Def get_error_details ():

... Return (2, 'second error details ')

...

>>> Errnum, errstr = get_error_details ()

>>> Errnum

2

>>> Errstr

'Second error details'

Note:A, B = <Some Expressions>The expression results are interpreted as tuples with two values.

If you want to interpret the result(A, <Other values>)As shown in the following figure:

>>> A, * B = [1, 2, 3, 4]

>>>

1

>>> B

[2, 3, 4]

This syntax also implies a method for quickly exchanging two variable values in Python:

>>> A = 5; B = 8

>>> A, B = B,

>>> A, B

(8, 5)

 

Special Method

There are some_ Intit __And_ Del __Methods have special meanings in the class. Special methods are used to simulate some built-in behaviors.

For example, you want to useX [Key]Index operations (just like in lists and meta groups), you only need to implement_ Getitem __Method.

By the way, Python implements the List class in this way!

Some useful special methods are listed in the following table. If you want to learn all the special methods, see (http://docs.python.org/py3k/reference/datamodel.html#special-method-names ).

Method Name

Explanation

_ Init _ (self ,...)

Called before an object is returned to become available

_ Del _ (Self)

Called before the object is destroyed

_ STR _ (Self)

Called when using the print function or STR ()

_ LT _ (self, other)

<) Is called when the value is smaller than the operator.

Other similar operators also have special methods (+,>, etc.) of objects)

_ Getitem _ (self, key)

Called when the X [Key] index operation is used

_ Len _ (Self)

It is called when built-in Len () function is used.

 

Single statement Block

We have seen that each statement block is separated based on its indentation level. But there is one exception.

If a statement block contains only one statement, you can put it in the same line, such as a condition statement or a loop statement.

The following example clearly illustrates this point:

>>> Flag = true

>>> If flag: Print 'yes'

...

Yes

Note that the preceding statement is placed in the same row and is not used as a separate block.

Although you can use this to shorten the program, I strongly recommend that you avoid it (except for error detection). The main reason is that you can easily add additional statements by using appropriate indentation.

 

LambdaExpression

LambdaThe statement is used to create and return a new function object at runtime.

#! /Usr/bin/Python

# Filename: Lambda. py

Def make_repeater (n ):

Return Lambda S: S * n

Twice = make_repeater (2)

Print (twice ('word '))

Print (twice (5 ))

Output:

$ Python lambda. py

Wordword

10

How code works:

When running, we use the FunctionMake_repeaterCreate a new function object and return it. One Lambda statement is used to create a function object.

Essentially, this Lambda requires a parameter followed by a single expression equivalent to the function body. The value of this expression will become the return value of the function.

Note thatPrintSuch statements cannot appear inLambdaCan only be an expression. (Note: print is a function in py3k, and the author is out ).

 

Think about it

Can we use Lambda to create a comparison function and provide itList. Sort ()?

Points = [{'X': 2, 'y': 3}, {'X': 4, 'y': 1}]

# Points. Sort (lambda A, B: CMP (A ['X'], B ['X'])

 

List Parsing(List comprehension)

List resolution is used to derive a new list from an existing list.

Suppose you have a number list, and you want to make all2Multiplied2And form a new list.

Similar problems are ideal for using list resolution.

#! /Usr/bin/Python

# Filename: list_comprehension.py

Listone = [2, 3, 4]

Listtwo = [2 * I for I in listone if I> 2]

Print (listtwo)

Output:

$ Python list_comprehension.py

[6, 8]

How code works:

When some conditions are met (If I> 2) We perform some operations (2 * I) To generate a new list. Note that the original list is not changed.

The benefit of list resolution is that it reduces the amount of sample code when we use a loop traversal element and store it in the new list.

 

Function receiving tuples and lists

There is a special way to use the form parameters of the function as tuples or dictionaries, that is, use the prefixes * and * respectively.

This method is useful when you need to get a variable number of real parameters in the function.

>>> Def powersum (power, * ARGs ):

... '''Return the sum of each argument raised to specified power .'''

... Total = 0

... For I in ARGs:

... Total + = POW (I, power)

... Return total

...

>>> Powersum (2, 3, 4)

25

>>> Powersum (2, 10)

100

BecauseARGsThe variable has a * prefix. Therefore, all additional arguments are stored in the ARGs as a tuples and passed to the function.

If the value * is changed to **, all the extra parameters will be treated as a dictionary key/value pair.

 

ExecAndEval

ExecFunctions are used to execute Python statements, but these statements are stored in strings or files rather than in the program itself.

For example, we can generate a string containing Python code at runtime, and then execute it using exec.

>>> Exec ('print ("Hello World ")')

Hello World

Similar to this,EvalFunction is used to execute a valid Python expression stored in a string. The following is a simple example.

>>> Eval ('2*3 ')

6

 

AssertStatement

AssertUsed to assert that an expression is true.

For example, make sure that the list in use has at least one element. Otherwise, an error is thrown, which is an ideal scenario for using assert.

When assert statement assertions fail,Asserterror.

>>> Mylist = ['item']

>>> Assert Len (mylist)> = 1

>>> Mylist. Pop ()

'Item'

>>> Mylist

[]

>>> Assert Len (mylist)> = 1

Traceback (most recent call last ):

File "<stdin>", line 1, in <module>

Assertionerror

Use assert with caution. Most of the time it is used to capture exceptions, handle problems or display errors to users, and then terminate the program.

 

ReprFunction

ReprFunction is used to obtain the regular string representation of an object. Interestingly, most of the timeEval (Repr (object ))EqualObject.

>>> I = []

>>> I. append ('item ')

>>> Repr (I)

"['Item']"

>>> Eval (Repr (I ))

['Item']

>>> Eval (Repr (I) = I

True

Basically, the Repr function is used to obtain the printable form of an object. You can define_ Repr __Method to Control the return value of Repr.

 

Summary

This chapter introduces more Python features. Although all features of Python are not introduced, it is sufficient to deal with most applications in practice.

Next we will consider how to further learn python.

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.