问题描述
在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版)支持旧样式"和新样式类.新样式类是从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).
这篇关于如何初始化基类(超级)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!