如何初始化基(超级)类? [英] How do I initialize the base (super) class?

查看:38
本文介绍了如何初始化基(超级)类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,考虑我有以下代码:

In Python, consider I have the following code:

class SuperClass(object):
    def __init__(self, x):
        self.x = x
        
class SubClass(SuperClass):
    def __init__(self, y):
        self.y = y
        # how do I initialize the SuperClass __init__ here?

如何在子类中初始化SuperClass __init__?我正在关注 Python 教程,但它没有涵盖这一点.当我在 Google 上搜索时,我找到了不止一种方法.处理这个问题的标准方法是什么?

How do I initialize the SuperClass __init__ in the subclass? I am following the Python tutorial and it doesn't cover that. When I searched on Google, I found more than one way of doing. What is the standard way of handling this?

推荐答案

Python(直到版本 3)支持old-style";和新式课程.新式类派生自 object 并且是您正在使用的,并通过 super(),例如

Python (until version 3) supports "old-style" and new-style classes. New-style classes are derived from object and are what you are using, and invoke their base class through super(), e.g.

class X(object):
  def __init__(self, x):
    pass

  def doit(self, bar):
    pass

class Y(X):
  def __init__(self):
    super(Y, self).__init__(123)

  def doit(self, foo):
    return super(Y, self).doit(foo)

因为 python 知道旧式和新式类,所以有不同的方法来调用基方法,这就是为什么你找到了多种方法来这样做.

Because python knows about old- and new-style classes, there are different ways to invoke a base method, which is why you've found multiple ways of doing so.

为了完整起见,旧式类使用基类显式调用基方法,即

For completeness sake, old-style classes call base methods explicitly using the base class, i.e.

def doit(self, foo):
  return X.doit(self, foo)

但既然你不应该再使用旧式,我也不会太在意这个.

But since you shouldn't be using old-style anymore, I wouldn't care about this too much.

Python 3 只知道新样式的类(无论是否从 object 派生).

Python 3 only knows about new-style classes (no matter if you derive from object or not).

这篇关于如何初始化基(超级)类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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