【问题标题】:Robot Framework keywords and InheritanceRobot Framework 关键字和继承
【发布时间】:2015-12-04 13:59:20
【问题描述】:

我有一个关键字库。我有一些类和子类,但是我遇到了继承和关键字被双重定义的问题。例如:

MyLib.py

class Class1:
  def __init__(self):
    pass

  def do_something_generic(self):
    #do stuff that is generic to all subclasses
    pass

class Subclass1(Class1):
  def __init__(self):
    pass

  def do_something_specific_to_subclass1(self):
    #something specific
    pass

class Subclass2(Class1):
  def __init__(self):
    pass

  def do_something_specific_to_subclass2(self):
    #something specific
    pass

具体的关键字工作正常,但当我尝试调用Do Something Generic 时,我得到Multiple keywords with name 'Do Something Generic' found。我可以用MyLib.Class1.Do Something Generic 完全限定库名称,但是有没有办法将Do Something Generic 定义为始终引用超类,因为该方法仅在那里定义并且只是由子类继承?

【问题讨论】:

    标签: python inheritance robotframework


    【解决方案1】:

    来自Robot Framework User Guide

    When the static library API is used, Robot Framework uses reflection to find out what public methods the library class or module implements.
    It will exclude all methods starting with an underscore,
    and with Java libraries also methods that are implemented only in java.lang.Object are ignored.
    All the methods that are not ignored are considered keywords.
    

    您是否考虑过使用_do_something_generic 函数添加辅助基类?您可以将其从__all__ 列表中排除。然后使用继承从Class1中的基类公开关键字。

    MyLibrary.py:
    __all__ = ['Class1', 'Subclass1', 'Subclass2']
    
    class BaseClass:
      def _do_something_generic(self):
        pass
    
    class Class1(BaseClass):
      def __init__(self):
        pass
    
      def do_something_generic(self):
        return self._do_something_generic()
    
    class Subclass1(BaseClass):
      def __init__(self):
        pass
    
      def do_something_specific_to_subclass1(self):
        a = self._do_something_generic()
        return (a, 3)
    
    class Subclass2(BaseClass):
      def __init__(self):
        pass
    
      def do_something_specific_to_subclass2(self):
        #something specific
        pass
    

    【讨论】:

    • 问题是有一些对 Class1 是通用的操作,但是做涉及子类的事情。例如,在我的例子中,Class1 指的是 ssh 连接库,而子类指的是我可以通过该 ssh 连接执行的特定操作,例如使用特定的 CLI。所以我想要一个 Disconnect 关键字来终止 ssh 连接,但我希望它对 ssh 库具有通用性。
    • 我想问题可能是机器人不是真正面向对象的,所以非 OO 机器人框架和它所构建的 OO python 代码之间的链接有点混乱
    【解决方案2】:

    我认为最好的解决方案是简单地将do_something_generic 移动到一个单独的类中,这样你的基类就只有辅助函数,没有公共关键字:

    class Class1:
      def __init__(self):
        pass
    
    class Subclass0(Class1):
      def do_something_generic(self):
        #do stuff that is generic to all subclasses
        pass
    

    虽然可以通过使用__slots__ 或__getattr__ 或修改self.__dict__ 等奇特的方法来解决此问题,但可能不值得这么麻烦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-17
      • 2014-02-27
      • 2013-09-06
      • 2013-07-07
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      相关资源
      最近更新 更多