EADST

Python 继承总结:父类与子类的调用关系

在 Python 面向对象编程中,继承 (Inheritance) 是一个核心机制。通过继承,子类可以复用父类的属性和方法,并在需要时覆盖或扩展它们。

本文用几个小例子来梳理:


1. 基本继承

class Parent:
    def hello(self):
        print("Hello from Parent")

class Child(Parent):
    pass

c = Child()
c.hello()   # 输出: Hello from Parent

👉 子类 Child 没有实现 hello 方法,因此调用时会沿着 MRO(方法解析顺序) 去父类找。


2. 方法重写(覆盖)

class Parent:
    def hello(self):
        print("Hello from Parent")

class Child(Parent):
    def hello(self):
        print("Hello from Child")

c = Child()
c.hello()   # 输出: Hello from Child

👉 子类里定义了同名方法,父类的方法就被覆盖(Override)。


3. 使用 super() 调用父类方法

有时希望子类在重写方法的同时,保留父类逻辑

class Parent:
    def hello(self):
        print("Hello from Parent")

class Child(Parent):
    def hello(self):
        super().hello()   # 调用父类方法
        print("Hello from Child")

c = Child()
c.hello()

输出:

Hello from Parent
Hello from Child

4. 父类 __call__ 调用子类方法

一个常见设计是父类在 __call__ 中固定调用几个“步骤方法”,子类只需重写步骤:

class Base:
    def __call__(self, data):
        data = self.step1(data)
        data = self.step2(data)
        return data

    def step1(self, data):
        return data + " base_step1 "

    def step2(self, data):
        return data + " base_step2 "

class Child(Base):
    def step2(self, data):
        return data + " child_step2 "

c = Child()
print(c("input"))

输出:

input base_step1  child_step2 

👉 父类 __call__ 会自动调用子类重写的 step2,这是 动态绑定 的体现。


5. 子类完全自定义 __call__

如果子类自己定义了 __call__,就会 覆盖掉父类的 __call__

class Base:
    def __call__(self, data):
        return self.process(data)

    def process(self, data):
        return data + " base "

class Child(Base):
    def __call__(self, data):
        return data + " child "

c = Child()
print(c("input"))

输出:

input child 

👉 父类的 __call__ 完全被替代,不会再执行。


6. 总结规律

  • 继承默认走父类 → 子类没实现的方法会去父类找。
  • 方法名相同 → 子类方法覆盖父类。
  • 父类内部调用子类方法 → Python 的动态绑定机制决定了:即使在父类中写 self.xxx(),只要子类实现了 xxx,就会调用子类的。
  • 子类定义 __call__ → 会完全替代父类 __call__ 的执行逻辑,除非显式 super().__call__()

✅ 记住一个口诀:

父类搭骨架,子类来填肉。 父类提供通用流程,子类通过覆盖方法来定制行为。

相关标签
About Me
XD
Goals determine what you are going to be.
Category
标签云
git-lfs 论文速读 GPTQ Claude uWSGI VPN Random 算法题 Web ONNX Logo NLTK 公式 Breakpoint 强化学习 Markdown VGG-16 Knowledge PyTorch Michelin Anaconda 云服务器 DeepSeek GPT4 printf Heatmap Numpy Hungarian 腾讯云 CEIR FP16 Linux BeautifulSoup 第一性原理 PyCharm HaggingFace OpenAI EXCEL Git Math Python Proxy Excel TSV 财报 WebCrawler YOLO Permission TensorRT Miniforge llama.cpp Qwen tqdm PDF Interview Magnet 顶会 Vim Password FastAPI OpenCV 证件照 Animate Nginx RGB Jupyter Bipartite HuggingFace 关于博主 图标 tar Jetson 多进程 Pickle Image2Text JSON LaTeX Quantization Disk Video Qwen2.5 Diagram SPIE Cloudreve Rebuttal Land FP64 git 域名 Windows Algorithm GIT BF16 Plate ModelScope Input API 签证 Bin Ubuntu GoogLeNet Baidu C++ TTS Django GGML SAM Freesound SQL IndexTTS2 Bert XML Pandas PDB Bitcoin scipy ms-swift Dataset LLM Tensor torchinfo Pillow Website 搞笑 News LLAMA Tracking Translation Docker Data Quantize XGBoost Datetime Google Gemma v2ray Hotel 飞书 LeetCode 论文 UNIX 报税 继承 Qwen2 MD5 QWEN 递归学习法 音频 Distillation NameSilo Github v0.dev Shortcut CUDA Firewall AI API网关 Harness Clash Streamlit Paper COCO Plotly OCR CAM Zip InvalidArgumentError Base64 UI Vmess Llama logger NLP RL CSV CLAP Safetensors Food RAR Use Card Mixtral icon CTC CC uwsgi mmap SVR BTC 阿里云 SQLite Tiktoken transformers 图形思考法 Augmentation Review Hilton LoRA Conda Pytorch CV Sklearn Domain hf Paddle Search ResNet-50 Ptyhon Attention FP8 FlashAttention WAN DeepStream TensorFlow Template Crawler ChatGPT PIP Transformers Color 版权 Agent Statistics 净利润 diffusers 多线程 VSCode FP32
站点统计

本站现有博文336篇,共被浏览939236

本站已经建立2649天!

热门文章
文章归档
回到顶部