我已将父类(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/