文档测试、装饰器

文档测试

import doctest
def mysum(x,y):
    '''
    >>> print(mysum(1,2))
    3
    '''
    return x + y

print(mysum(1,2))
doctest.testmod()

运行结果:

3

但是如果函数发生改动:

import doctest
def mysum(x,y):
    '''
    >>> print(mysum(1,2))
    3
    '''
    return x + y +1

print(mysum(1,2))
doctest.testmod()

那么输出就会有变化,测试没通过:

4
**********************************************************************
File "/Users/miraco/Library/Preferences/PyCharm2018.1/scratches/test.py", line 5, in __main__.mysum
Failed example:
    print(mysum(1,2))
Expected:
    3
Got:
    4
**********************************************************************
1 items had failures:
   1 of   1 in __main__.mysum
***Test Failed*** 1 failures.

装饰器

from time import ctime

def deco(func):
    def decorator(*args, **kwargs):
        print('[%s]  %s() is called' % (ctime(), func.__name__))
        return func(*args, **kwargs)
    return decorator

@deco
def foo():
    print('Hello, Python')

foo()

运行结果:

[Wed Nov 14 19:33:17 2018]  foo() is called
Hello, Python

你可能感兴趣的:(文档测试、装饰器)