class A:
    def __init__(self):
        print("world")

class B(A):
    def __init__(self):
       print("hello")

B()  # output: hello

在我使用过的所有其他语言中,超级构造函数都是隐式调用的.在Python中如何调用它?我希望是super(self),但这不起作用.

推荐答案

与其他答案一样,在Python-3中,有多种方法可以调用超类方法(包括构造函数).x简化了流程:

Python-3.x

class A(object):
 def __init__(self):
   print("world")

class B(A):
 def __init__(self):
   print("hello")
   super().__init__()

Python-2.x

在python 2中.x、 您必须调用稍微详细一点的版本super(<containing classname>, self),它相当于super()as/the docs.

class A(object):
 def __init__(self):
   print "world"

class B(A):
 def __init__(self):
   print "hello"
   super(B, self).__init__()

Python相关问答推荐

不同数据类型的Python成员变量不会在具有相同优先级的不同线程中更新

如何判断. text文件中的某个字符,然后读取该行

Pandas滚动分钟,来自其他列的相应值

了解shuffle在NP.random.Generator.choice()中的作用

Matplotlib轮廓线值似乎不对劲

opencv Python稳定的图标识别

如何使用Python中的clinicalTrials.gov API获取完整结果?

分组数据并删除重复数据

仅从风格中获取 colored颜色 循环

Pandas 填充条件是另一列

如何自动抓取以下CSV

Python,Fitting into a System of Equations

为什么抓取的HTML与浏览器判断的元素不同?

在vscode上使用Python虚拟环境时((env))

Pandas计数符合某些条件的特定列的数量

如何根据一列的值有条件地 Select 前N组?

将scipy. sparse矩阵直接保存为常规txt文件

寻找Regex模式返回与我当前函数类似的结果

如何在两列上groupBy,并使用pyspark计算每个分组列的平均总价值

Gekko中基于时间的间隔约束