python - 继承时需要初始化父类吗?

标签 python super

如果我继承自一个类并且不更改方法中的任何内容,是否需要使用 super 来初始化父类的方法?

class A:

   def __init__(self):
       self.html = requests.get("example.com").text


class B(A):

    def __init__(self):
        # is this needed?
        super(B, self).__init__()

    def new_method(self):
        print self.html

最佳答案

因为您在类 B 中创建了一个 __init__ 方法,它覆盖A 中的方法。如果你想执行它,你必须使用 super(),是的。

但是,如果您在 B.__init__ 中没有做任何else,您也可以忽略它:

class A:
   def __init__(self):
       self.html = requests.get("example.com").text

class B(A):
    def new_method(self):
        print self.html

如果您想除了 A.__init__() 所做的任何事情,那么创建一个B.__init__()< 是有意义的 方法,并从该方法调用父级 __init__

关于python - 继承时需要初始化父类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27536343/

相关文章:

python - PyCharm TensorFlow 警告 - 类型 'Variable' 没有预期的属性 '__sub__'

python - 使用 __init__() 方法理解 Python super()

Android SQLiteOpenHelper 错误 - 对 super 的调用必须是构造函数中的第一条语句

当父对象不从对象继承时,Python 2.x super __init__ 继承不起作用

python - 机器学习模型预测错误结果

python - 计算大序列过零的不同结果

python - ORA-01036 : illegal variable name/number (cx_Oracle)

python - 如何使用 Python @singledispatch 注册 Typing.Callable?

python - 多重继承调用顺序

java - Exception 子类中 `Super` 关键字的影响