Python使用字符串的方式调用类的实例方法
背景
在整理新的web自动化测试框架的时候,遇到一个问题,定义的关键字函数,是在WebKeyword
类中,然后用例使用Excel
管理,取出来关键字一列,然后通过这个关键字去调用WebKeyword
类中的关键字方法,因为调用类中的实例方法,必须要使用对象.实例方法
的形式调用,所以eval()
函数在此就无法使用,只能换一种方式,经过查阅资料得知,可以使用operator
模块下的methodcaller
方法解决这个问题,下面简单介绍下此方法的用法。
methodcaller
方法用法
1. 导包
from operator import methodcaller
2. 调用无参的实例方法
methodcaller("函数名")(类对象)
示例:
from operator import methodcaller
class A:
def eat(self):
return "吃东西"
a = A()
result = methodcaller("eat")(a)
print(result)
执行结果:
3.调用有参的实例方法
# 单个参数
methodcaller("函数名","参数")(类对象)
# 多个参数
methodcaller("函数名","参数1","参数2","参数n")(类对象)
# OR 通过解包进行传递参数
list = ["参数1","参数2","参数n"]
methodcaller("函数名",*list)(类对象)
示例(就以我实际的用法展示):
关键字类WebKeyword
:
class WebKeyword:
def openBrowser(self, browser_type):
print("打开{}浏览器".format(browser_type))
测试用例类
import pytest
from .webKeyWord import WebKeyword
from operator import methodcaller
# Excel读取的数据
excel_data = [[1, "打开谷歌浏览器", "openBrowser", "chrome"],
[2, "打开火狐浏览器", "openBrowser", "firefox"],
[3, "打开IE浏览器", "openBrowser", "ie"]]
# 初始化关键字类
kw = WebKeyword()
@pytest.mark.parametrize("case", excel_data)
def test(case):
# 获取关键字
keyWord = case[2]
# 获取参数
param = case[3]
# 使用methodcaller调用关键字
methodcaller(keyWord, param)(kw)
执行结果:
【完】