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

如何不修改父类SmartPhone,正确继承方法实现指定输出?

如何在不修改父类的前提下实现子类继承并输出指定内容?

问题描述

我是一名计算机科学大一学生,现在需要实现继承自SmartPhone类的Xiaomi和Huawei类,让给定的测试代码生成指定输出。但要求不能修改父类SmartPhone的代码,我之前通过修改父类的check方法实现了效果,但不符合要求,想知道正确的做法。

给定的父类代码:

class SmartPhone:
    def __init__(self, name):
        self.name = name
    def check(self):
        print("The phone is working properly")

测试代码:

#Write your code here
f = Xiaomi("Redmi Note 8")
c = Huawei("Y9")
f.check()
print("=========================")
c.check()
print("=========================")

要求输出:

This is Xiaomi Redmi Note 8
The phone is working properly
=========================
This is Huawei Y9
The phone is working properly
=========================

正确解法

核心思路是在子类中重写check方法:先打印子类专属的标识文本,再调用父类的check方法来输出通用的工作状态提示。这样既不需要修改父类,又能满足输出要求。

具体代码实现:

class SmartPhone:
    def __init__(self, name):
        self.name = name
    def check(self):
        print("The phone is working properly")

# 子类实现
class Xiaomi(SmartPhone):
    def check(self):
        # 先打印子类专属信息
        print(f"This is Xiaomi {self.name}")
        # 调用父类的check方法输出通用内容
        super().check()

class Huawei(SmartPhone):
    def check(self):
        print(f"This is Huawei {self.name}")
        super().check()

# 测试代码
f = Xiaomi("Redmi Note 8")
c = Huawei("Y9")
f.check()
print("=========================")
c.check()
print("=========================")

思路解释

  • 子类重写check方法后,当调用子类实例的check时,会优先执行子类的自定义逻辑。
  • 使用super().check()可以直接复用父类的check方法逻辑,避免重复编写打印通用提示的代码,同时严格遵守“不修改父类”的要求。
  • 这种方式既保留了父类的原有功能,又给子类添加了专属的输出内容,完美匹配指定的输出格式。

内容的提问来源于stack exchange,提问作者Md. Shahriar Hasan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 09:33:16