1. 程式人生 > 其它 >pytest文件4-fixture之conftest.py

pytest文件4-fixture之conftest.py

python-裝飾器

當一個函式中,不同邏輯混雜在一起的時候,程式的可讀性會大打折扣。這個時候,可以考慮用一種叫做“裝飾器”的東西來重新整理程式碼。

def xx1(被裝飾函式):
def xx2(如果被裝飾函式有引數那麼輸入):
xxxxxxxxxxxxxxx
被裝飾函式(如果被裝飾函式有引數那麼輸入)
xxxxxxxxxxxxxxx
如果被裝飾函式中含有reture則需要返回被裝飾函式
沒有則不需要
reture xx2

沒有返回值的函式

import time


def display_time(func):
    """
    記錄時間裝飾器
    :return:
    """

    def function():
        t1 = time.time()
        func()
        print(time.time() - t1)

    return function


@display_time
def count_run_number():
    for i in range(1, 1000):
        print(i)


count_run_number()

帶有返回值的函式

import time


def display_time(func):
    """
    記錄時間裝飾器
    :return:
    """

    def function():
        t1 = time.time()
        result = func()
        print(time.time() - t1)
        return result

    return function


@display_time
def count_run_number():
    count = 0
    for i in range(1, 100000):
        if i % 2 == 0:
            count += 1
    return count


count_run_number()

帶有引數的函式

import time


def display_time(func):
    """
    記錄時間裝飾器
    :return:
    """

    def function(*args,**kwargs):
        t1 = time.time()
        result = func(*args,**kwargs)
        print(time.time() - t1)
        return result

    return function


@display_time
def count_run_number(num):
    count = 0
    for i in range(1, num):
        if i % 2 == 0:
            count += 1
    return count


count_run_number(100000000)