For example, we will introduce 25 hidden features in Python and the python25 feature.
Note: well-known techniques such as generator, decorator, and switch variable are ignored.
1. function parameter unpack
This is a common story:
def foo(x, y): print x, y alist = [1, 2]adict = {'x': 1, 'y': 2} foo(*alist) # 1, 2foo(**adict) # 1, 2
2. chained comparison Operators
>>> x = 3>>> 1 < x < 5True>>> 4 > x >=3True
3. Pay attention to the default function parameters.
>>> def foo(x=[]):... x.append(1)... print x...>>> foo()[1]>>> foo()[1, 1]
Safer practices:
>>> 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]). If the key cannot be found in the dictionary dct, get will return default_value.
sum[value] = sum.get(value, 0) + 1
5. formatting with keywords
>>> print "Hello %(name)s !" % {'name': 'James'}Hello James !>>> print "I am years %(age)i years old" % {'age': 18}I am years 18 years old
Updated formatting:
>>> print "Hello {name} !".format(name="James")Hello James !
Some template engines are getting better :)
6.... Else syntax
>>> 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>>>
The else statement block is executed after the loop ends, unless the break is executed in the loop block.
7. Special dict method _ missing __
Introduced after Python 2.5. If the key cannot be found, this method is executed.
>>> 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]
This is similar to collections. defaultdict, isn't it?
>>> from collections import defaultdict>>> dct = defaultdict(list)>>> dct["foo"][]>>> dct["bar"].append("Hello")>>> dctdefaultdict(<type 'list'>, {'foo': [], 'bar': ['Hello']})
8. step size parameters of the slice operation
You can also use step-1 to reverse the linked list:
9. Another string connection
>>> Name = "Wang" "Hong">>> Name'WangHong'
Connect multiple rows:
>>> Name = "Wang" \... "Hong" >>> Name 'wanghong'10. "_" in the Python Interpreter "_">>> Range (4) [0, 1, 2, 3] >>> _ [0, 1, 2, 3]
_ That is, the value returned by the Python interpreter last time
11. Python Descriptor
Python descriptors are magical in Python, and methods are all descriptors. No more examples
12. 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)]14. try/except/else try: put_4000000000_volts_through_it(parrot)except Voom: print "'E's pining!"else: print "This parrot is no more!"finally: end_sketch()
15. print redirection output to file
>>> print >> open("somefile", "w+"), "Hello World"
Note the opening mode: "w +" instead of "w". Of course, "a" is acceptable.
16. ellipsis
In Python3, you can directly use the ellipsis Syntax:
Python 3.2 (r32:88445, Oct 20 2012, 14:09:50)[GCC 4.5.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> ...Ellipsis
In Python2?
>>> class C(object):... def __getitem__(self, item):... return item...>>> C()[1:2, ..., 3](slice(1, 2, None), Ellipsis, 3)>>>
17. unpack the tuples in Python3
I really hope Python2 will do the same:
>>> a, b, *rest = range(10)>>> a0>>> b1>>> rest[2, 3, 4, 5, 6, 7, 8, 9]>>>
Of course, you can also retrieve the last one:
>>> first, second, *rest, last = range(10)>>> first0>>> second1>>> last9>>> rest[2, 3, 4, 5, 6, 7, 8]
18. pow () has a third parameter.
We all know that the built-in function pow, pow (x, y) is x ** y
However, it can also have the third parameter:
>>> pow(4, 2, 2)0>>> pow(4, 2, 3)1
In fact, the third parameter is used to evaluate the modulo: pow (x, y, z )? ==? (X ** y )? % Z
Note that the built-in pow and math. pow are not a function, and the latter only accepts two parameters.
19. enumerate has a second parameter.
Enumerate is awesome. You can give us an index and a sequence value pair, but it has a second parameter:
>>> lst = ["a", "b", "c"]>>> list(enumerate(lst, 1))[(1, 'a'), (2, 'b'), (3, 'c')]
This parameter indicates the starting value of the index.
20. explicitly declare a set
Create a new set. We will:
>>> set([1,2,3])
This can be written after Python 2.7:
>>> {1,2,3}set([1, 2, 3])
21. Use slice to delete a part of a sequence
>>> a = [1, 2, 3, 4, 5, 6, 7]>>> a[1:4] = []>>> a[1, 5, 6, 7]
Of course, you can use dela [].
Remove even items (even index ):
>>> a = [0, 1, 2, 3, 4, 5, 6, 7]>>> del a[::2]>>> a[1, 3, 5, 7]
22. An isinstance can receive a tuples.
This is really little known. We can use isinstance (x, (float, int) to determine whether x is a number:
>>> isinstance(1, (float, int))True>>> isinstance(1.3, (float, int))True>>> isinstance("1.3", (float, int))False
In the third test, you can add str to the tuples to see what is going on:
>>> isinstance("1.3", (float, int, str))True
That is, the relationship between the or in the tuples. If it is one of the instances, True is returned.
23. Infinite recursion in the dictionary
>>> a, b = {}, {}>>> a['b'] = b>>> b['a'] = a>>> a{'b': {'a': {...}}}
Of course, you can create an infinite loop in the linked list:
>>> a, b = [], []>>> a.append(b)>>> b.append(a)>>> a[[[...]]]
I really don't know how to use it, but it's fun, isn't it?
24. Python can recognize numbers in Unicode
So, Python is awesome:
>>> int(u'1234')1234
It can be recognized not only by ASCII strings, but also by Unicode.
25. Inaccessible Properties
The answer is too bad :)
>>> class O(object):pass...>>> o = O()>>> setattr(o, "can't touch this", 123)>>> o.can't touch this File "<stdin>", line 1 o.can't touch this ^SyntaxError: EOL while scanning string literal>>> File "<stdin>", line 1 o.can't touch this ^SyntaxError: EOL while scanning string literal
However, if you can use setattr to set attributes, you can use getattr to retrieve them.