是否有一种正确的方法来实现一个 subclass,其方法签名与其在 Python 中的 super class 不同?

Is there a proper way to implement a subclass with a different method signature than its super class in Python?

我已经将超级 class 定义为其他开发人员将编写子classes 来实现的正式接口,但是该方法的参数会因实现而异:

class FormalInterface:
  """ Subclasses will have varying arguments for formal_method """
  def formal_method(*args, required_arg=0):
    raise NotImplemented('Implement me')

  def get_arguments():
    """ Tells the user what arguments need to be passed """
    raise NotImplemented('Implement me')


class MyImplementationOf(FormalInterface):
  def formal_method(concrete_arg1, conrete_arg2, required_arg=0)
    # impelementation...

  def get_arguments():
    return 'concrete_arg1', 'concrete_arg2', 'required_arg'

这是合法的 python 代码,但是关于重新定义函数签名的警告比比皆是。

在这种情况下,我忽略警告是否正确?或者是否有我应该考虑的更 Pythonic 的方法?

super-considered-super blog post 中有关于如何处理这种情况的建议。

just 的一种方法是仅使用关键字参数,剥离您需要的参数并使用 **kwargs 将剩余参数委托给其他方法:

class A:
    def m(self, *, x, y):
        print(f'{type(self)=}   {x=}   {y=}')

class B(A):
    def m(self, *, z, **kwargs):
        super().m(**kwargs)
        print(f'{type(self)=}   {z=}')

像这样调用方法:

>>> A().m(x=10, y=20)
type(self)=<class '__main__.A'>   x=10   y=20
>>> B().m(x=10, y=20, z=30)
type(self)=<class '__main__.B'>   x=10   y=20
type(self)=<class '__main__.B'>   z=30