Python - 练习

单例设计模式


class Dog(object):
    # 保存单例引用
    singleton = None
    # 初始化一次的标记
    init_flag = False

    # 分配内存空间
    def __new__(cls, *args, **kwargs):
        if cls.singleton is None:
            # 调用父类方法创建空间,返回引用
            cls.singleton = super().__new__(cls)
        print('__new__ run...')

        # 返回引用给__init__ 进行初始化
        return cls.singleton

    def __init__(self):
        if Dog.init_flag:
            return
        print('初始化 run...')
        Dog.init_flag = True


dog1 = Dog()
print(dog1)
dog2 = Dog()
print(dog2)

"""
__new__ run...
初始化 run...
<__main__.Dog object at 0x000002227BA43EB0>
__new__ run...
<__main__.Dog object at 0x000002227BA43EB0>
"""

打印长方形

"""
需求在控制台打印如下图形:
*********
*********
*********
*********
*********
*********
*********
*********
*********
"""

# 大圈,控制行号
row = 1
while row <= 9:
    col = 1
    # 小圈控制列
    while col <= 9:
        print("*", end="")
        col += 1
    print("")
    row += 1

打印九九乘法表


# while 写法
row = 1
while row <= 9:  # 大圈,控制行号
    col = 1
  
    while col <= row:    # 小圈控制列 , 注意col < row
        print(f"{col} * {row} = {col * row}", end="\t")
        col += 1
    print("")
    row += 1


# for循环写法:
for x in range(1, 10):
    for y in range(1, x + 1):
        print(f"{y} * {x} = {y * x}", end="\t")
    print("")

输出:

1 * 1 = 1	
1 * 2 = 2	2 * 2 = 4	
1 * 3 = 3	2 * 3 = 6	3 * 3 = 9	
1 * 4 = 4	2 * 4 = 8	3 * 4 = 12	4 * 4 = 16	
1 * 5 = 5	2 * 5 = 10	3 * 5 = 15	4 * 5 = 20	5 * 5 = 25	
1 * 6 = 6	2 * 6 = 12	3 * 6 = 18	4 * 6 = 24	5 * 6 = 30	6 * 6 = 36	
1 * 7 = 7	2 * 7 = 14	3 * 7 = 21	4 * 7 = 28	5 * 7 = 35	6 * 7 = 42	7 * 7 = 49	
1 * 8 = 8	2 * 8 = 16	3 * 8 = 24	4 * 8 = 32	5 * 8 = 40	6 * 8 = 48	7 * 8 = 56	8 * 8 = 64	
1 * 9 = 9	2 * 9 = 18	3 * 9 = 27	4 * 9 = 36	5 * 9 = 45	6 * 9 = 54	7 * 9 = 63	8 * 9 = 72	9 * 9 = 81

一行代码打印九九乘法表

"""
注意:
1.左边for循环可以访问右边for循环的变量。
2.右边for不能访问左边for循环的变量
"""
# 正确写法
print("\n".join(["  ".join(f"{x}*{y} = {x * y}" for y in range(1, x + 1)) for x in range(1, 10)]))



# 此类写法错误
data1 = "\n".join(["  ".join(f"{x} * {y} = {x * y}" for x in range(1, 10)) for y in range(1, x+1)])
print(data1)


解析:
print("  ".join(f"{x}" for x in range(1, 10))) 
# out:1  2  3  4  5  6  7  8  9

print(["  ".join(f"{x} * {y} = {x*y}" for x in range(1, y+1)) for y in range(1, 10)])
# out:
['1 * 1 = 1', '1 * 2 = 2  2 * 2 = 4', '1 * 3 = 3  2 * 3 = 6  3 * 3 = 9', '1 * 4 = 4  2 * 4 = 8  3 * 4 = 12  4 * 4 = 16', '1 * 5 = 5  2 * 5 = 10  3 * 5 = 15  4 * 5 = 20  5 * 5 = 25', '1 * 6 = 6  2 * 6 = 12  3 * 6 = 18  4 * 6 = 24  5 * 6 = 30  6 * 6 = 36', '1 * 7 = 7  2 * 7 = 14  3 * 7 = 21  4 * 7 = 28  5 * 7 = 35  6 * 7 = 42  7 * 7 = 49', '1 * 8 = 8  2 * 8 = 16  3 * 8 = 24  4 * 8 = 32  5 * 8 = 40  6 * 8 = 48  7 * 8 = 56  8 * 8 = 64', '1 * 9 = 9  2 * 9 = 18  3 * 9 = 27  4 * 9 = 36  5 * 9 = 45  6 * 9 = 54  7 * 9 = 63  8 * 9 = 72  9 * 9 = 81']

字符串find 和 index 方法的区别

find(el): 找不到的时候不会由异常,返回-1
index(el): 找不到的时候会抛出异常,ValueError: substring not found 

[{},{},{}] 调整为[(),(),()]

使用场景:读取json文件,使用parameterized 做参数化

def build_data(filepath):
    """
    功能:读取json文件组装成[(), (), ()]格式的数据
    :param filepath: 指定处理的json文件
    :return: 组装完成的列表数据
    """
    # 读取json数据
    my_list = []
    with open(filepath, encoding='utf-8') as f:
        dict_data = json.load(f)
        print(dict_data)
       
        for x in dict_data:
            # 方式一:
            # tup_gen = (y for y in x.values())
            # my_tup = tuple(tup_gen)
            # 方式二:
            my_tup = tuple(x.values())
            my_list.append(my_tup)
      return my_list


if __name__ == '__main__':
    ret = build_data('./login.json')
    print(tuple(ret))
    print(*tuple(ret))

# out:
"""
[{'desc': '登陆成功', 'mobile': '13800000002', 'password': '123456', 'status_code': 200, 'success': True, 'code': 10000, 'message': '操作成功'}, 
{'desc': '用户名错误', 'mobile': '1380003342', 'password': '123456', 'status_code': 200, 'success': False, 'code': 20001, 'message': '用户名或密码错误'}]

[('登陆成功', '13800000002', '123456', 200, True, 10000, '操作成功'), ('用户名错误', '1380003342', '123456', 200, False, 20001, '用户名或密码错误')]

"""

[{},{},{}] 调整为((),(),())

场景:
[{},{},{}] 一般是json.load() 的数据格式,但是测试做参数化的时候使用不是该格式,所以需要转化为如下格式:

  • parameterized 使用的数据格式是[(),(),()] 【上面实现过】
  • ddt 使用的数据格式是(),(),() 【可以将((),(),()) 拆包】

需求:
如何将[{},{},{}] 转换为(),(),()

实现:将[{},{},{}] 转换为((),(),()), 然后进行拆包操作

"""
# read_json_data.py

def build_data(filepath):
    """
    功能:读取json文件组装成[(), (), ()]格式的数据
    :param filepath: 指定处理的json文件
    :return: 组装完成的列表数据
    """
    # 读取json数据
    my_list = []
    with open(filepath, encoding='utf-8') as f:
        data = json.load(f)
        print(data)
        for x in data:
            my_tup = tuple(x.values())
            my_list.append(my_tup)

    return my_list


if __name__ == '__main__':
    ret = build_data('./login.json')
    print(tuple(ret))
    print(*tuple(ret))

# out:
"""
(('登陆成功', {'mobile': '13800000002', 'password': '123456'}, {'status_code': 200, 'success': True, 'code': 10000, 'message': '操作成功'}), ('用户名错误,登陆失败', {'mobile': '13800003342', 'password': '123456'}, {'status_code': 200, 'success': False, 'code': 20001, 'message': '用户名或密码错误'}), ('密码错误,登陆失败', {'mobile': '13800000002', 'password': '123456abc'}, {'status_code': 200, 'success': False, 'code': 20001, 'message': '用户名或密码错误'}))

('登陆成功', {'mobile': '13800000002', 'password': '123456'}, {'status_code': 200, 'success': True, 'code': 10000, 'message': '操作成功'}) ('用户名错误,登陆失败', {'mobile': '13800003342', 'password': '123456'}, {'status_code': 200, 'success': False, 'code': 20001, 'message': '用户名或密码错误'}) ('密码错误,登陆失败', {'mobile': '13800000002', 'password': '123456abc'}, {'status_code': 200, 'success': False, 'code': 20001, 'message': '用户名或密码错误'})

"""
# test.py

import unittest
import ddt

from ni01_eai_login_api import LoginApi
from read_json_data import build_data

# 读取测试用例数据
test_data = tuple(build_data('./login.json'))

@ddt.ddt
class TestLogin(unittest.TestCase):

    # @ddt.data((1, {'hhh': 'xxxx'}, {'qqq': 'www'}), (1, {'hhh': 'xxxx'}, {'qqq': 'www'}))
    @ddt.data(*test_data)
    @ddt.unpack
    def test_01(self, title, body, expect):
        print(f"title is {title}, body is {body}, expect is {expect}" )

if __name__ == '__main__':
    unittest.main()

找到列表中两个不同元素的最大积

>>>l = [-10,3,2,7,8]
>>> from itertools import combinations
>>> combinations(l, 2)
<itertools.combinations object at 0x0000022385A34B30>
>>> list(combinations(l,2))
[(-10, 3), (-10, 2), (-10, 7), (-10, 8), (3, 2), (3, 7), (3, 8), (2, 7), (2, 8), (7, 8)]
>>> max(a*b for a,b in combinations(l,2))
56


https://zhuanlan.zhihu.com/p/343374115
posted @ 2022-01-09 21:08  chuangzhou  阅读(45)  评论(0编辑  收藏  举报