python __getattr__ 方法在自动化测试中的应用

内容部分来自网络

python中调用a.xx,内部就是a.__getattr__(xx)或者getattr(a, xx),而a.xx(),其中xx实现了__call__()方法,即调用了getattr(a, xx)()。

通过重写__getattr__(xx)方法实现返回值调用

举个栗子:

class Page:
def __init__(self, ):
pass

def __getattr__(self, loc):
if loc not in self.locators.keys():
raise Exception
print(loc)
by, val = self.locators[loc]
return by, val


class CommonLoginPage(Page):
locators = {
'username': ('id', 'account'),
'password': ('name', 'password'),
'loginBtn': ('id', 'submit')
}

def login(self, ):
print(self.username)
print(self.password)


dome = CommonLoginPage()
dome.login()

# 结果
# username
# ('id', 'account')
# password
# ('name', 'password')

使用__getattr__方法即可将元素定位放在一个字典中统一管理。

posted @ 2021-07-11 19:23  mik99  阅读(87)  评论(0编辑  收藏  举报