python - 具有相似主体的覆盖方法
问题描述
我有两个班:一和二
class One:
# self.a, self.b, self.c
# ...
def foo(self):
self.a.foo()
self.b.bar()
self.c.hmm(1,2,3)
class Two(One):
# super(Two, self).__init__()
# self.d
# ...
def foo(self):
self.a.foo()
self.b.bar()
self.d.wow()
self.c.hmm(4,5,6)
One 和 Two 的foo()
方法非常相似,以至于我觉得我在复制粘贴代码。我知道我可以foo2()
在 One 中有一个单独的方法来执行共享代码并foo()
为不同的值添加参数,但我想知道是否有更好的方法来做到这一点。
解决方案
要从超类扩展方法,您可以使用super
.
class One:
...
def foo(self):
self.a.foo()
self.b.bar()
self.c.hmm(1,2,3)
class Two(One):
...
def foo(self):
super().foo()
self.d.wow()
请注意,这不会保留调用方法的顺序。因此,如果该顺序很重要,您必须重写整个foo
方法。
推荐阅读
- java - SocketTimeoutException:使用 NGINX 配置读取超时
- asp.net - 如何在 Asp.net MVC 中获取选中复选框的值?
- r - c(...) 的用户函数默认参数之一
- javascript - 如何字符串替换数组中的符号并拆分?
- sql - 如何加入日历表以获得主表中没有值的空值?
- xml - 重新编号节点
- c++ - 测量 std::future 对象可用之前的时间
- ios - 在使用 SQLite3 插入值后关闭视图控制器后,如何刷新表视图?
- ios - xcode永远上传file.ips
- c# - 库中的 AutoMapper 配置文件类 - AutoMapperMappingException:缺少类型映射配置或不支持的映射错误