06 November 2016

Python Note

operator.itemgetter/attrgetter

simple usage is like:

>>> f=itemgetter(2)
>>> l=(1,2,3)
>>> f(l)
3

It's very useful when applied to sorting, e.g.,

## sorting students by weight (suppose student has attr. student.weight)
 sorted(students, key=attrgetter('weight')

get class name of an instance

if (module.__class__.__name__==unicode)

Update: it's better to use a classmethod. See the next note.

classmethod/staticmethod

classmethod receives the class it's called on as the first argument (as cls); regular instance method gets the instance it's called on as the first argument (as self); staticmethod gets either of them.

classmethos is useful for alternative constructors.

difference betweent == and is

a = [1,2]
b = [1,2]
a == b # returns True
a is b # returns False

== checks the value, while is checks the object itself. See this SO thread http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python

Misc

  1. By default, . in regex doesn't match newline (\s matches newline)
  2. use douban pypi
pip install -i http://pypi.douban.com/simple/ gevent


blog comments powered by Disqus