我从我的一年级 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?
潇潇雨雨
蝴蝶不菲
相关分类