Welcome to Python-Note’s documentation!

装饰器

装饰器的本质是什么?

Remember, that the @decorator syntax is just syntactic sugar; the syntax:

@property
def foo(self):
    return self._foo

really means the same thing as

def foo(self):
    return self._foo
foo = property(foo)

描述器

贼麻烦。

标准库

Python中的标准库是非常强大的,本章简单介绍一下关于python标准库里面的东西。

dis

这个库可以把python字节码转换成类似于汇编语言的东西,比如我定义一个myfunc:

def myfunc(alist):
    return len(alist)

然后调用dis,来查看运行的过程:

>>> dis.dis(myfunc)
  2           0 LOAD_GLOBAL              0 (len)
              3 LOAD_FAST                0 (alist)
              6 CALL_FUNCTION            1
              9 RETURN_VALUE

doctest

这个库是用来进行文档测试的,在文档中写出这个方法的使用过程。

调用方法是:

import doctest
doctest.testmod()

如此一来就可以进行相关的测试

解决python2-3的兼容问题

six

解决Python2-3的兼容问题,可以使用 six 来做许多工作。

from six.moves import urllib
# import urllib.request

如此以来,可以替换 urllib

__future__

__init__ 包中引入 from __future__ import division 可以将python2中的除法变为python3

编码技巧

由 clean code 想到,极好的代码是应该通过函数名,变量等自成逻辑,不应该在源代码以及文档上耗费时间。

Notifier

OSX

import os

# The notifier function
def notify(title, subtitle, message):
    t = '-title {!r}'.format(title)
    s = '-subtitle {!r}'.format(subtitle)
    m = '-message {!r}'.format(message)
    os.system('terminal-notifier {}'.format(' '.join([m, t, s])))

# Calling the function
notify(title    = 'A Real Notification',
       subtitle = 'with python',
       message  = 'Hello, this is me, notifying you!')

IPython使用技巧

使用IPython查看当前变量

This might help you, though it’s not exactly what Spyder offers and is much simpler:

To get a list of all currently defined variables, run who :

In [1]: foo = 'bar'

In [2]: who
foo

For more detail, run whos:

In [3]: whos
Variable   Type    Data/Info
----------------------------
foo        str     bar

For a complete list of built-in functions see Magic Commands

Indices and tables