【发布时间】:2020-09-29 13:10:51
【问题描述】:
我从一年级 CS 学生的朋友那里得到了这个问题。
问题:实现Xiaomi和Huawei类继承的设计
来自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