51Testing软件测试论坛

标题: 这样神奇的代码该怎么理解呢? [打印本页]

作者: 测试积点老人    时间: 2019-8-22 11:09
标题: 这样神奇的代码该怎么理解呢?
最近在看uiautomator的Python封装,代码中使用param_to_property的装饰器,就可以实现
d.open.notification(),这样的转换不知该如何理解。
google了一天了,帮小弟解惑,谢谢啦
  1. def param_to_property(*props, **kwprops):
  2.     if props and kwprops:
  3.         raise SyntaxError("Can not set both props and kwprops at the same time.")

  4.     class Wrapper(object):

  5.         def __init__(self, func):
  6.             self.func = func
  7.             self.kwargs, self.args = {}, []

  8.         def __getattr__(self, attr):
  9.             if kwprops:
  10.                 for prop_name, prop_values in kwprops.items():
  11.                     if attr in prop_values and prop_name not in self.kwargs:
  12.                         self.kwargs[prop_name] = attr
  13.                         return self
  14.             elif attr in props:
  15.                 self.args.append(attr)
  16.                 return self
  17.             raise AttributeError("%s parameter is duplicated or not allowed!" % attr)

  18.         def __call__(self, *args, **kwargs):
  19.             if kwprops:
  20.                 kwargs.update(self.kwargs)
  21.                 self.kwargs = {}
  22.                 return self.func(*args, **kwargs)
  23.             else:
  24.                 new_args, self.args = self.args + list(args), []
  25.                 return self.func(*new_args, **kwargs)
  26.     return Wrapper
  27. 。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
  28. ...
  29. 。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
  30. @property   
  31. def open(self):
  32.         '''
  33.         Open notification or quick settings.
  34.         Usage:
  35.         d.open.notification()
  36.         d.open.quick_settings()
  37.         '''
  38.         @param_to_property(action=["notification", "quick_settings"])
  39.         def _open(action):
  40.             if action == "notification":
  41.                 return self.server.jsonrpc.openNotification()
  42.             else:
  43.                 return self.server.jsonrpc.openQuickSettings()
  44.         return _open
复制代码



作者: qqq911    时间: 2019-8-23 10:38
还是自己封装的好
作者: litingting0214    时间: 2019-8-23 11:41
还没有用过,我觉得还是自己封装比较好
作者: libingyu135    时间: 2019-8-23 11:43
坐等
作者: jingzizx    时间: 2019-8-23 12:24

作者: luomin19    时间: 2019-8-24 17:27
坐等。。。。。。。。。。。。。。。。。。




欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2