super(MyObject, self).__init__() 在类 MyObject __init__() 函数中做什么? [英] What do super(MyObject, self).__init__() do in class MyObject __init__() function?

查看:52
本文介绍了super(MyObject, self).__init__() 在类 MyObject __init__() 函数中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我读过这样的python27代码,

I have read a python27 code like this,

我知道'super'的意思是父类构造函数,

I know 'super' means father class constructor function,

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

but I cannot understand why these two classes call themselves' constructor function '__init__',

好像没有什么实际作用.

it seems don't have any practical effect.

推荐答案

这些是 Python 中一些非常基本的 OO 方法.阅读此处.

These are some pretty basic OO methods in Python. Read here.

superself 类似:

super() 让你避免显式引用基类,它可以很好.但主要优点是多重继承,在那里可以发生各种有趣的事情.请参阅标准文档超级如果你还没有.

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.

(来自这个答案)

这是一个 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,但对于基类.

You can see that super is calling the base class (the class that the current class inherits), followed by an access modifier, accessing the base class' .__init__() method. It's like self, but for the base class.

这篇关于super(MyObject, self).__init__() 在类 MyObject __init__() 函数中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆