You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中ABC抽象类子类重写__init__是否需调用super().__init__?

子类构造方法相关问题解答

先看你提供的代码示例:

父类定义

from abc import ABC, abstractmethod
import mysql.connector
from mysql.connector import MySQLConnection, MySQLCursor

# 假设以下为已定义的常量和异常类
HOST = "xxx"
USERNAME = "xxx"
PASSWORD = "xxx"
PORT = 3306
DATABASE_SCHEMA = "xxx"

class DatabaseException(Exception):
    pass

class Database(ABC):
    @abstractmethod
    def open_db_connection(self):
        pass

子类定义

class MySQLdatabase(Database):
    def __init__(self):
        self.db_connection = None
        self.db_cursor = None
        self.record = None
        self.record_dict = None

    def open_db_connection(self) -> tuple[MySQLConnection, MySQLCursor]:
        try:
            self.db_connection = mysql.connector.connect(
                host=HOST,
                user=USERNAME,
                password=PASSWORD,
                port=PORT,
                database=DATABASE_SCHEMA
            )
            if self.db_connection.is_connected():
                self.db_cursor = self.db_connection.cursor(prepared=True, dictionary=True)
                return self.db_connection, self.db_cursor
        except mysql.connector.Error as e:
            raise DatabaseException("error", f"while connecting to db: Database Connection Failed! error: {e}")

问题1:MySQLdatabase类是否需要调用super().__init__()?

不需要。你的父类Database没有自定义__init__方法,它继承的ABC类默认构造方法也没有任何必须执行的初始化逻辑(比如无需要初始化的实例属性、无前置操作)。当前子类的__init__只需要处理自身的实例变量,完全没必要调用父类的构造方法。

问题2:重写__init__后,父类Database及ABC类的__init__是不是都不会执行?

没错。Python中子类重写__init__后,若没有显式调用super().__init__(),所有父类(包括直接父类Database和间接父类ABC)的构造方法都不会自动执行。如果之后你给Database类添加了自定义的__init__逻辑(比如初始化通用属性),那时候就必须在MySQLdatabase的__init__里调用super().__init__(),才能保证父类的初始化逻辑正常运行。


内容的提问来源于stack exchange,提问作者64rl0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 03:13:17