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

我从我的一年级 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 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

=========================

我的解决方案:


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 here

class 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?


九州编程
浏览 89回答 2
2回答

潇潇雨雨

您需要的是实现check调用父方法的方法:class SmartPhone:     def __init__(self, name):         self.name = name     def check(self):          print(“The phone is working properly”)#Write your code hereclass 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(“=========================”)

蝴蝶不菲

当重写超类的方法时,您需要调用 super。这意味着,def check(self):    print(f"This is Xiaomi {self.name}")    super.check()    // codes for overriding
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python