机器人框架关键字和继承

2024-04-16 10:06:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在我的lib.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来始终引用超类,因为方法只在那里定义,并且只是由子类继承的?在


Tags: toself定义initdefpass关键字do
2条回答

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

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__,或者修改{}来解决这个问题,但这可能不值得麻烦。在

来自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函数添加helper基类?您可以将其从__all__列表中排除。然后使用继承公开Class1中基类的关键字。在

^{pr2}$

相关问题 更多 >