【问题标题】:What is a basic example of single inheritance using the super() keyword in Python?在 Python 中使用 super() 关键字的单继承的基本示例是什么?
【发布时间】:2010-11-13 12:36:07
【问题描述】:

假设我设置了以下类:

class Foo:
     def __init__(self, frob, frotz):
          self.frobnicate = frob
          self.frotz = frotz
class Bar:
     def __init__(self, frob, frizzle):
          self.frobnicate = frob
          self.frotz = 34
          self.frazzle = frizzle

我如何(如果可以的话)在这种情况下使用 super() 来消除重复代码?

【问题讨论】:

标签: python inheritance constructor super


【解决方案1】:

假设您希望类 Bar 在其构造函数中设置值 34,这将起作用:

class Foo(object):
     def __init__(self, frob, frotz):
          self.frobnicate = frob
          self.frotz = frotz

class Bar(Foo):
     def __init__(self, frob, frizzle):
          super(Bar, self).__init__(frob, frizzle)
          self.frotz = 34
          self.frazzle = frizzle


bar = Bar(1,2)
print "frobnicate:", bar.frobnicate
print "frotz:", bar.frotz
print "frazzle:", bar.frazzle

但是,super 引入了其自身的复杂性。参见例如super considered harmful。为了完整起见,这里是没有super的等效版本。

class Foo(object):
     def __init__(self, frob, frotz):
          self.frobnicate = frob
          self.frotz = frotz

class Bar(Foo):
     def __init__(self, frob, frizzle):
          Foo.__init__(self, frob, frizzle)
          self.frotz = 34
          self.frazzle = frizzle


bar = Bar(1,2)
print "frobnicate:", bar.frobnicate
print "frotz:", bar.frotz
print "frazzle:", bar.frazzle

【讨论】:

  • 你为什么要通过超类构造函数设置 Bar.frotz = frizzle 然后单独设置为 34?你不应该只有 __init__(frob,34) 吗?
  • 是的,这也可以,而且会更干净。这个例子相当做作(在构造函数中设置一个常量),但我试图尽可能接近原始示例。
  • 我不知道这是否是一个好方法......考虑超级构造函数对 frotz 执行操作并且 frizzle 是一个类的情况,您的代码不会运行或太多更糟糕的事情可能会发生。
  • 看到超级被认为是超级! - PyCon 2015 youtube.com/watch?v=asrMKBVHtSw
【解决方案2】:

在 Python >=3.0 中,像这样:

class Foo():
    def __init__(self, frob, frotz)
        self.frobnicate = frob
        self.frotz = frotz

class Bar(Foo):
    def __init__(self, frob, frizzle)
        super().__init__(frob, 34)
        self.frazzle = frizzle

在此处阅读更多信息:http://docs.python.org/3.1/library/functions.html#super

编辑:正如另一个答案中所说,有时只使用Foo.__init__(self, frob, 34) 可能是更好的解决方案。 (例如,在使用某些形式的多重继承时。)

【讨论】:

  • 明确一点,这只是python >= 3.0。对于较旧的蟒蛇(但仅限于那些具有“新型类”的蟒蛇),@ire_and_curses 的答案描述了需要做的事情。
猜你喜欢
  • 2015-06-07
  • 1970-01-01
  • 2018-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-05
  • 1970-01-01
相关资源
最近更新 更多