python - super(MyObject, self).__init__() 在类 MyObject __init__() 函数中做什么?

标签 python inheritance super

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 中一些非常基本的 OO 方法。阅读 here .

superself 类似:

super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven't already.

(来自此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,但用于基类。

关于python - super(MyObject, self).__init__() 在类 MyObject __init__() 函数中做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38586279/

相关文章:

java - 在Java中,我们如何知道构造函数中的super()何时完成?

python - 理解 Python super() 和 __init__() 方法

java - super() 如何在构造函数中工作

javascript - 每当我通过 ajax 调用它时,Django Rest 框架都会用 AnonymousUser 替换我当前经过身份验证的用户?

Django 将 `choices` 添加到继承的模型字段

python - 如何在基类的函数上使用装饰器,并在继承基类时让装饰器作用于该函数

python - 动态添加/覆盖property属性的setter和getter

python - 在 python shell 中执行 bash 的复杂查找命令

python - 在 python 中使用正则表达式捕获重复组

python - 如何在 Golang 中解开一个 python 对象