【问题标题】:What do super(MyObject, self).__init__() do in class MyObject __init__() function? [duplicate]super(MyObject, self).__init__() 在类 MyObject __init__() 函数中做了什么? [复制]
【发布时间】:2016-11-29 21:20:31
【问题描述】:
class MyObject1(object):
    def __init__(self):
        super(MyObject1, self).__init__()
        pass

class MyObject2(object):
    def __init__(self, arg):
        super(MyObject2, self).__init__()
        pass

我看过这样的python27代码,

我知道'super'是指父类构造函数,

但我不明白为什么这两个类称自己为'构造函数'__init__',

好像没有什么实际作用。

【问题讨论】:

标签: python inheritance super


【解决方案1】:

这些是 Python 中一些非常基本的 OO 方法。阅读here

superself 相似:

super() 让您避免显式引用基类,这 可以很好。但主要优势在于多重继承, 各种有趣的事情都可能发生的地方。请参阅标准文档 超级如果你还没有。

(来自answer

下面是super 的示例:

class Animal(object):
     def __init__(self, speed, is_mammal):
          self.speed = speed
          self.is_mammal = is_mammal

class Cat(Animal):
     def __init__(self, is_hungry):
          super().__init__(10, True)
          self.is_hungry = is_hungry

barry = Cat(True)
print(f"speed: {barry.speed}")
print(f"is a mammal: {barry.is_mammal}")
print(f"feed the cat?: {barry.is_hungry}")

可以看到super在调用基类(当前类继承的类),后面跟着一个访问修饰符,访问基类的.__init__()方法。类似于self,但用于基类。

【讨论】:

    猜你喜欢
    • 2022-12-08
    • 2010-10-12
    • 2019-04-21
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    相关资源
    最近更新 更多