想要学好python自动化测试,当然不可缺少的知识就是python基础知识,有不少同学python学了一遍又一遍,得不到实际运用,所以时间一长,基础知识慢慢还是归零,既浪费了时间又打消了自己的积极性。
从我们python接口自动化测试实战的一期学员说起,有同学看到代码里面的args及*kwargs非常困惑,这就是典型的基础知识没有掌握。
*args用来将参数打包成tuple给函数体调用
"""
*args的使用方法:
用来将参数打包成tuple给函数体调用
"""
# 举例1
def func1(*args):
print(args, type(args))
func1(1)
# 举例2
def func2(x, y, *args):
print(x, y, args)
func2(1, 2, 3, 4, 5)
执行结果:
D:\tttesting\workspace\venv\Scripts\python3.exe D:/tttesting/test.py
(1,) <class 'tuple'>
1 2 (3, 4, 5)
**kwargs打包关键字参数成dict给函数体调用
"""
**kwargs的使用方法:
打包关键字参数成dict给函数体调用
"""
# 举例1
def func3(**kwargs):
print(kwargs, type(kwargs))
func3(a=2)
# 举例2
def func4(**kwargs):
print(kwargs)
func4(a=1, b=2, c=3)
def func(arg, *args, **kwargs):
print(arg, args, kwargs)
func(6, 7, 8, 9, a=1, b=2, c=3)
执行结果:
D:\tttesting\workspace\venv\Scripts\python3.exe D:/tttesting/test.py
{'a': 2} <class 'dict'>
{'a': 1, 'b': 2, 'c': 3}
6 (7, 8, 9) {'a': 1, 'b': 2, 'c': 3}
Process finished with exit code 0
如下部分内容摘自我们python接口自动化测试实战一期课程给学员新增的基础知识,你是否都已经掌握了呢?希望对你有所帮助。
# -*- coding:utf8 -*-
"""方法"""
# def common(name, value):
# print("这是{}".format(name))
# print(value)
#
#
# def study_data_type_v2():
# common("字符", "欢迎光临1213abc")
# common("列表", [1, "字符串", dict(name='tt', age=123), [1, 3, 4, 5, ], ])
# print("还有其他有序数据类型:元祖、集合等")
# common("字典", {"name": 'yyt', 'age': 12})
"""1. 简单数据结构"""
def study_data_type_v1():
print("我就是字符串")
print("下面是列表")
print([1,
"字符串",
dict(name='tt', age=123),
[1, 3, 4, 5, ],
]) # 这里加一个对象
print("还有其他有序数据类型:元祖、集合等")
print("下面是字典")
print({"name": 'yyt',
'age': 12}
)
"""2. 简单数据类型的操作"""
# region 字符串
str_a = "我喜欢"
str_b = "吃饭"
str_c = "睡觉"
test_1 = "这是一个组合" + "的字符串" # 字符串拼接 1
test_2 = "_".join([str_a, str_b, str_c]) # 字符串拼接 2
test_2 = test_2.split("-") # 字符串分割
test_3 = str(test_2).replace("_", "&&") # 字符串的替换
str_d = "字符串的判断"
bool_result = bool("判断" in str_d)
str_e = "字符串的遍历"
for i in str_e:
print(i)
for index, i in enumerate(str_e):
print("字符串中序号为{}的汉字是{}".format(index, i))
# endregion
# region 列表
list_a = [1, 3, 5, 4]
list_b = ["a", "b", "c"]
list_c = [1, 1, 1, 1]
list_d = ['d']
list_b.extend(list_d) # 两个列表合并
list_b[-1] = 'e' # 赋值
list_b.append('f') # 追加
split_list_1 = list_b[1:2]
split_list_2 = list_b[:2]
split_list_3 = list_b[1:]
# 判断
bool_result = bool("a" in list_b)
# 排序
list_a.sort(reverse=True)
# 遍历
for i in list_a:
print(i)
# endregion
# region字典
dict_a = dict(name='中国', age=19)
dict_b = {"name": "中国",
"age": 19
}
dict_a['age'] = 20 # 赋值
dict_a.update(sex='女') # 更新
# 判断
bool_result = bool("name" in dict_b)
keys = dict_a.keys()
# 遍历
for k, v in dict_a.items():
print("key:{key} value:{value}".format(key=k, value=v))
# endregion
list_e = [i*10 for i in range(0, 5)] # 推到式
""" 对象 """
class BaseObj(object):
class_host = 'http://www.class_dev.com'
def __init__(self, **kwargs):
"""origin doc"""
self.host = "http://www.dev.com"
self.db = "test"
# print("最最最常用的构造函数")
# self.update_value(**kwargs)
# def __repr__(self):
# print("根据我的意思打印host:{}".format(self.host))
# print(self.__dict__)
#
# def __enter__(self):
# print("我正在连接{}的DB".format(self.db))
#
# def __exit__(self, exc_type, exc_val, exc_tb):
# print("我需要关闭掉当前的{}连接".format(self.db))
# def set_doc(self, doc):
# self.__doc__ = doc
#
# def doc(self):
# return self.__doc__
#
# def update_value(self, **kwargs):
# if kwargs:
# for attribute_name in kwargs.keys():
# setattr(self, attribute_name, kwargs.get(attribute_name))
#
def get_value(self, name, default=None):
"""
获取对象的属性值
:param name: 属性名
:param default: 如果没有返回的默认值
:return:
"""
value = getattr(self, name, default)
if value is None:
return default
else:
return value
#
# def clear_value(self):
# for k, v in vars(self).items():
# setattr(self, k, None)
# region 修改属性-例子: 统一修改接口访问host
print(BaseObj.class_host)
c = BaseObj()
# 修改类属性
BaseObj.class_host = 'http://www.class_test.com'
a = BaseObj()
b = BaseObj()
print(a.class_host)
print(b.class_host)
print(c.class_host) # 这个地址会变改变吗?
# 修改对象a的属性
a.host = 'http://www.test.com'
print(a.host)
print(b.host)
# 修改对象b的属性
b.host = 'http://www.test.com'
print(a.host)
print(b.host)
# endregion
# region 放开上面对象中各种方法之后的效果你知道吗?
a = BaseObj()
b = BaseObj(name='兔子', age=19)
# endregion
# region 继承
class UserInfo(BaseObj):
def __init__(self, **kwargs):
self.name = "狗子"
self.age = 1
super(UserInfo, self).__init__(**kwargs)
def set_name(self, name):
self.name = name
user_info = UserInfo(name="哈斯奇", db="dev") # 看看里面的属性
user_info.name = "泰迪"
user_info.set_name("吉娃娃")
name = user_info.get_value("name")
default_value = user_info.get_value("dddd", "默认值")
# endregion
# region装饰器
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print('call %s():' % func.__name__)
print('args = {}'.format(*args))
return func(*args, **kwargs)
return wrapper
@log
def test(p):
print(test.__name__ + " param: " + p)
test("I'm a param")
# endregion
以上内容希望对你能有所帮助。另外我们的python接口自动化测试实战二期课程正在预售中,名额有限,月底截止报名,如感兴趣,左下角阅读原文直接进入二期课程预售,或联系如下微信咨询: