什么是跳过父方法的pythonic方法?

时间:2016-10-07 13:07:20

标签: python inheritance

class A:
  def open_spider(self, spider):
    #do some hacking

class B(A):
  def open_spider(self, spider):
    super(B, self).open_spider(spider)
    #something else

现在我希望C调用A的方法而不是B,这至少可以通过两种方式完成:

  class C(B):
    def open_spider(self, spider):
      A.open_spider(self, spider)
      #do things

  class C(B):
    def open_spider(self, spider):
      super(B, self).open_spider(spider)
      #do things

3 个答案:

答案 0 :(得分:6)

你可以用第二种方式做到这一点。但是我必须说孩子跳过父母方法并且打电话给祖父母的部分是错误的,你应该再次看看你的设计并考虑一下。

答案 1 :(得分:1)

使用第二种方法;这是super 类作为其第一个参数的一个原因。

答案 2 :(得分:0)

<强>更新

Harry Percival states中的Test-Driven Web Development with Python

  

此处的个人观点:我本可以使用super,但我不愿意   在需要参数时使用super,例如获得祖父母方法。   我发现Python 3的super()没有很棒的args可以立即获得   家长。其他任何事情都容易出错,而且我觉得它很难看。

在那里,他给出的解决方案是直接调用祖父母类及其方法。

以下内容:

class C(B):
    def get_queryset(self):
        return A.get_queryset(self)

这是你的第一种方法。我一定会采纳它。谢谢!

这是暂时覆盖父类方法的“一次性”黑客攻击。意图是“完成工作”,直到重构发生。

否则,您可能需要重新考虑类的设计,Alex指出。

我有同样的问题,最后我提出了以下解决方案:

class A:
  def get_queryset(self):
    # Do not hack around

class B(A):
  from_c = False

  def get_queryset(self):
    if self.from_c:
        # Here goes the C hack
    else:
        # Here goes the B hack

class C(B):
    from_c = True

know that

  

应该有一个 - 最好只有一个 - 显而易见的方法。

我有一种感觉,我的“解决方案”只是黑客入侵的第三种方式。但是:

  • 我不是荷兰人。
  • 在你的例子的范围内,这个技巧既复杂又实用,但并不复杂
相关问题