python - 在Python中是否有一种正确的方法来实现具有与其父类(super class)不同的方法签名的子类?

标签 python interface signature super subclassing

我已将父类(super class)定义为正式接口(interface),其他开发人员将编写子类来实现该接口(interface),但是该方法的参数将因实现而异:

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中有关于如何处理这种情况的建议。 .

一种方法是仅使用关键字参数,去掉您需要的参数,并使用 **kwargs 将剩余参数委托(delegate)给其他方法:

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

关于python - 在Python中是否有一种正确的方法来实现具有与其父类(super class)不同的方法签名的子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60107237/

相关文章:

python - 如何为嵌套列表中的特定字符串创建子列表

python - threading.Thread 如何在 Python 中产生剩余的量子?

java - 需要帮助编译此迭代和接口(interface)程序

encryption - 在 javacard 上使用 Curve25519

html - HTML 签名中的鼠标悬停效果

python - 无法安装geopandas

python - 如何测试一个矩阵是否是旋转矩阵?

Android Fragments 基础知识 : why? 这在概念上是错误的吗?

interface - 关于接口(interface)的极端菜鸟查询

email - Powershell 打开带签名的电子邮件草稿