Give an example of 25 hidden features in Python _python

Source: Internet
Author: User
Tags eol pow stdin unpack

Note: The familiar tips for generators, adorners, and exchange variables are ignored here
1. function parameter Unpack

It's a cliché:

def foo (x, y):
  print x, y
 
alist = [1, 2]
adict = {' x ': 1, ' Y ': 2}
 
foo (*alist) # 1, 2
foo (**adict) # 1, 2

2. Chain comparison operator

>>> x = 3
>>> 1 < x < 5
true
>>> 4 > x >=3
True

3. Note The default parameters of the function

>>> def foo (x=[]):
...   X.append (1)
...   Print x ...
>>> foo ()
[1]
>>> foo ()
[1, 1]

A safer approach:

>>> def foo (x=none):
...   If X is None:
....     x = [] ...   X.append (1)
...   Print x ...
>>> foo ()
[1]
>>> foo ()
[1]
>>>

4. The dictionary has a Get () method

Dct.get (Key[,default_value]), when a key is not found in the dictionary DCT, get returns Default_value

Sum[value] = sum.get (value, 0) + 1

5. Formatted with keywords

>>> print "Hello% (name) s!"% {' name ': ' James '}
hello James!
>>> print "I am years% (age) I years old"% {' age ': @
I am years years old

To update some of the formatting:

>>> print "Hello {name}!". Format (name= "James")
Hello James!

Quick some of the template engine flavor:
6. For...else Grammar

>>> for I in (1, 3, 5):
...   If I% 2 = 0:
...     Break
... else:
...   Print "Var i is always an odd"
...
var i is always an odd
>>>

Else statement blocks are executed after the end of the loop, unless the break is executed in a loop block
7. Special methods of Dict __missing__

That was introduced after Python 2.5. This method is executed when the key is not found.

>>> class Dict (Dict):
...  def __missing__ (self, key):
...   Self[key] = []
...   return Self[key]
...
>>> DCT = Dict ()
>>> dct["foo"].append (1)
>>> dct["foo"].append (2)
> >> dct["foo"]
[1, 2]

It's like Collections.defaultdict, isn't it?

>>> from collections import defaultdict
>>> DCT = defaultdict (list)
>>> dct["foo" ]
[]
>>> dct["Bar"].append ("Hello")
>>> DCT
defaultdict (<type ' list ' > , {' foo ': [], ' Bar ': [' Hello ']}]

8. Step parameters for slicing operations

You can also use the step size-to reverse the list:

9. Another kind of string connection

>>> name = "Wang" "Wanghong"
>>> name
' "

Connect Multiple lines:

>>> Name = "Wang" \
... "" "
>>> Name
' wanghong '
10. "_"
 
>>> Range (4)
[0, 1, 2, 3]
>>> _
[0, 1, 2, 3] in the Python interpreter

_ that is the last value returned by the Python interpreter
Python Descriptor

The Python descriptor is a magical thing in Python, and methods are all descriptors. No more examples
Zen

Import this

13. Nested list derivation

>>> [(I, J) for I in range (3) for J in Range (i)]
[(1, 0), (2, 0), (2, 1)]
try/except/else
 
Try:
 put_4000000000_volts_through_it (Parrot)
except Voom:
 print "' E ' pining!"
else:
 print "This parrot is no more!"
Finally:
 End_sketch ()

Print redirect output to file

>>> Print >> open ("Somefile", "w+"), "Hello World"

Note Open mode: "w+" and not "w", of course "a" is OK
16. Ellipsis

In Python3 you can use the ellipsis directly in this grammar:

Python 3.2 (r32:88445, OCT, 14:09:50)
[GCC 4.5.2] on linux2
Type ' help ', ' copyright ', ' credits ' or ' lice NSE "For more information.
>>> ... Ellipsis

What about the Python2?

>>> class C (object):
... def __getitem__ (self, item):
...  Return Item
...
>>> C () [1:2, ..., 3]
(Slice (1, 2, None), ellipsis, 3)
>>>

Tuple unpack in Python3

I really wish Python2 would have done the same thing:

>>> A, B, *rest = Range (Ten)
>>> a
0
>>> b
1
>>> Rest
[2, 3, 4, 5, 6, 7, 8, 9]
>>>

Of course, you can also take out the last one:

>>> A, second, *rest, last = range
>>>
0 (
>>> second
1)
>>> last
9
>>> rest
[2, 3, 4, 5, 6, 7, 8]

Pow () and a third parameter

We all know that the built-in function Pow,pow (x,y) is X**y

But it can also have a third parameter:

>>> POW (4, 2, 2)
0
>>> Pow (4, 2, 3)
1

In fact, the third parameter is to seek modulo: pow (x,y,z)? (x**y)?%z

Note that the built-in POW and math.pow are not a function, which accepts only 2 parameters
Enumerate also has a second parameter.

Enumerate is awesome, you can give us index and sequence values, but it has a second argument:

>>> LST = ["A", "B", "C"]
>>> list (Enumerate (LST, 1))
[(1, ' a '), (2, ' B '), (3, ' C ')]

This parameter is used to: indicate the starting value of the index
20. Explicit declaration of a set

To create a new collection, we will:

>>> set ([1,2,3])

After Python 2.7, you can write this:

>>> {1,2,3}
set ([1, 2, 3])

21. Use a slice to delete a segment of a sequence

>>> a = [1, 2, 3, 4, 5, 6, 7]
>>> a[1:4] = []
>>> a
[1, 5, 6, 7]

Of course, with Dela[1:4] is also possible

Get rid of even-numbered items (even index):

>>> a = [0, 1, 2, 3, 4, 5, 6, 7]
>>> del A[::2]
>>> a
[1, 3, 5, 7]

Isinstance can receive a tuple

This is really little known, we can use Isinstance (x, (Float,int)) to determine whether X is the number:

>>> isinstance (1, (float, int))
true
>>> isinstance (1.3, (float, int))
true
>>> isinstance ("1.3", (float, int))
False

So for the third Test, you can see what's going on by adding STR to the tuple:

>>> isinstance ("1.3", (float, int, str))
True

That is, the relationship within that tuple, as long as one of the instances returns true
23. Infinite recursion in a dictionary

>>> A, B = {}, {}
>>> a[' b '] = b
>>> b[' a '] = a
>>> a
{' B ': {' a ': {.. .}}}

Of course you can create an infinite loop in a list:

>>> A, B = [], []
>>> a.append (b)
>>> b.append (a)
>>> a
[[[...]]]

I really don't know what it's for, but it's fun, isn't it?
Python can recognize numbers in Unicode

So Python is awesome:

>>> int (u ' 1234 ')
1234

Not only are ASCII strings recognizable, even Unicode can be.
25. Properties that cannot be accessed

The person who answered the answer is too bad:

 
>>> class O (object):p
...
>>> o = O ()
>>> setattr (o, "can ' t touch this", 123)
>>> O.can ' t touch this
 File &L T;stdin> ", line 1
  o.can ' t touch this
           ^
syntaxerror:eol while scanning string literal
>>>< C10/>file "<stdin>", line 1
  o.can ' t touch this
           ^
syntaxerror:eol while scanning string literal

However, you can use the SetAttr to set the properties and use the GetAttr to remove

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.