为了账号安全,请及时绑定邮箱和手机立即绑定

如何在不改变父类的情况下正确继承父类的方法?

如何在不改变父类的情况下正确继承父类的方法?

九州编程 2023-09-19 14:08:02
我从我的一年级 CS 学生朋友那里得到了这个问题。问题:Xiaomi实现和Huawei继承自 class 的类的设计SmartPhone,以便以下代码生成以下输出:给定代码:class SmartPhone:     def __init__(self, name):         self.name = name     def check(self):          print(“The phone is working properly”)     #Write your code heref = Xiaomi(“Redmi Note 8”)c = Huawei(“Y9”)f.check()print(“=========================”)c.check()print(“=========================”)输出应该是:This is Xiaomi Redmi Note 8The phone is working properly=========================This is Huawei Y9The phone is working properly=========================我的解决方案:class SmartPhone:     def __init__(self, name):         self.name = name     def check(self):         print(self.__str__()) #changing parent class         print('The phone is working properly')#Write your code hereclass Xiaomi(SmartPhone):    def __str__(self):        return f'This is Xiaomi {self.name}'class Huawei(SmartPhone):    def __str__(self):        return f'This is Huawei {self.name}'f = Xiaomi('“Redmi Note 8”')c = Huawei('“Y9”')f.check()print('=========================')c.check()print('=========================')我的解决方案通过更改父类来根据需要提供正确的输出。但据说不改变父类SmartPhone,只构建子类来产生相同的结果。那么,如何在不改变父类的情况下产生结果呢SmartPhone?
查看完整描述

2 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

您需要的是实现check调用父方法的方法:


class SmartPhone:

     def __init__(self, name):

         self.name = name


     def check(self):

          print(“The phone is working properly”)



#Write your code here

class Xiaomi(SmartPhone):

    def check(self):

        print(f"This is Xiaomi {self.name}")

        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(“=========================”)


查看完整回答
反对 回复 2023-09-19
?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

当重写超类的方法时,您需要调用 super。这意味着,


def check(self):

    print(f"This is Xiaomi {self.name}")

    super.check()

    // codes for overriding


查看完整回答
反对 回复 2023-09-19
  • 2 回答
  • 0 关注
  • 55 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信