【问题标题】:How to inherit a method properly from parent class without changing the parent class?如何在不更改父类的情况下从父类正确继承方法?
【发布时间】:2020-09-29 13:10:51
【问题描述】:

我从一年级 CS 学生的朋友那里得到了这个问题。

问题:实现XiaomiHuawei类继承的设计 来自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 类的情况下生成结果呢?

【问题讨论】:

  • def check(self): print('This is Xiaomi ...'); super().check()...?在调用父级的原始方法之前,覆盖每个子级中的 check 方法以输出该附加消息...?
  • 知道了。非常感谢。我忘记调用超级函数了。

标签: python python-3.x class oop inheritance


【解决方案1】:

你需要实现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(“=========================”)

【讨论】:

  • 知道了。非常感谢。
【解决方案2】:

覆盖超类中的方法时需要调用 super。意思是,

def check(self):
    print(f"This is Xiaomi {self.name}")
    super.check()
    // codes for overriding

【讨论】:

    猜你喜欢
    • 2015-11-25
    • 2018-04-05
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    相关资源
    最近更新 更多